C#での初期化子あれこれ

C#で、よく使い良く忘れる、配列初期化、オブジェクト初期化、コレクション初期化の例を並べてみる。

配列の初期化

string[] week = { "日曜日", "月曜日", "火曜日", "水曜日", "木曜日", "金曜日", "土曜日" };
int[] prime = { 2, 3, 5, 7, 11 };

Listの初期化

List<string> PrefectureNameList = new List<string> { "Tokyo", "Osaka", "Fukuoka" };
List<int> PointList = new List<int> { 70, 98, 30 };

Dictionaryの初期化

Dictionary<string, string> PrefectureEnToJp = new Dictionary<string, string> { 
    ["Tokyo"] = "東京", 
    ["Osaka"] = "大阪", 
    ["Fukuoka"] = "福岡" 
};
Dictionary<string, int> PrefectureCode = new Dictionary<string, int> {
    ["Tokyo"] = 13,
    ["Osaka"] = 27,
    ["Fukuoka"] = 40
 };

匿名型の初期化

var pet = new { Age = 10, Name = "Pochi" };

プロパティの初期化

public class Student
{
	public string FirstName { get; set; } = "Gonbei";
	public string LastName { get; set; } = "Nanashi";
	public string Class { get; set; }

	public List<int> PointList { get; set; } = new List<int>();
}

プロパティ(Property)の初期化は、VS2015で使えるようになった。

オブジェクト(クラス)の初期化

Student myStudent = new Student()
{
	FirstName = "Taro",
	LastName = "Yamada",
	Class = "B",
	PointList = new List<int> { 40, 30, 80 }
};

もちろん、オブジェクトの初期化時に、内包するListも初期化可能。

クラスを含めたのList型の初期化

List<Student> studentList = new List<Student>()
{
    new Student() { 
        FirstName = "Taro", 
        LastName = "Yamada", 
        PointList = new List<int> { 10, 20 } 
    },
    new Student() { 
        FirstName = "Hanako", 
        LastName = "Suzuki", 
        PointList = new List<int> { 30, 25, 10 } },
    null
};

あまり使い道無い気もするけど、コレクションの中身をnullで初期化もできる。

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>