LoginSignup
1
4

More than 1 year has passed since last update.

C#のプロパティ初期化

Last updated at Posted at 2022-06-29

C#のプロパティについて、
以下のような、=を使っての初期化と、

public List<Shop> Shops { get; set; } = new List<Shop>();
public int X { get; set; } = 10;

以下のような、=> を使った書き方の違いって何?

public string ItemUnitName => Item.UnitName;

と思って調べた。
https://ufcpp.net/study/csharp/ap_ver6.html#sec-expression-bodied

また、プロパティとインデクサーの場合は、get-only なものに限って、{ get { return } } を、以下のように置き換えれます。 (一方、get/set 両方持つものに対する省略記法はありません。今まで通りの書き方が必要です。)

なるほど、get-only なものに限って、は可能だけれど、get/set 両方持つものは今まで通りの書き方が必要なのですね。

public List<Shop> Shops => new List<Shop>();

と、

public List<Shop> Shops { get; } = new List<Shop>();

は同じ意味ということか。
<<
コメント欄で訂正いただきました。ありがとうございます。

同じ意味ではありません。
前者は Shops にアクセスするたび new List() が呼ばれますが、後者は自動生成される readonly フィールドが初期化されるだけです。
そのため、前者は Shops.Add で要素を追加しても、次アクセスした際には Count が 0 になっているはずです。

じゃあ、これは?このCount1とCount2は同じ?

    public class Polygon1
    {
        private Point[] _vertexes;
        public int Count1 => _vertexes.Length;
        public int Count2 { get; } = _vertexes.Length;
    }

と思ったけど、Count2 はエラーになる。

A field initializer cannot reference the non-static field, method, or property 'name'.

non-static フィールドで、プロパティの初期化はできないのね。
=>を使った初期化だと、このエラーを回避できるのか。

1
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4