C# literals:
- Array Declaration and Initialization:
//the long way
int[] numbers = new int[5] {1, 2, 3, 4, 5};
//shorter
int[] numbers = new int[] {1, 2, 3, 4, 5};
//the shortest, more friendly way:
int[] numbers = {1, 2, 3, 4, 5}; - Object Initializers
//Object, (well, this is so obvious, but anyway I add it here to have a complete reference)
myPerson p = new Person(){
Name: "xuan",
Age: 30
}; - Collections initializers:
List<int> myList = new List<int>(){1,2,3};
List<Cat> cats = new List<Cat>
{
new Cat(){ Name = "Sylvester", Age=8 },
new Cat(){ Name = "Whiskers", Age=2 },
new Cat(){ Name = "Sasha", Age=14 }
};
And now, the one that I tend to have more doubts with, thinking that I'm just borrowing it from other dynamic languages, but not, this short nice syntax for Dictionaries is perfectly valid C#:
var data = new Dictionary<string, string>
{
{ "test", "val" },
{ "test2", "val2" }
};
No comments:
Post a Comment