Collection initializers were introduced with C# 3.0. They provide a simpler way to add objects to collections:
Example without the collection initializer:
List<animal> animals = new List<animal>();
animals.Add( new animal { Color = “Brown”, Age = 2 } );
animals.Add( new animal { Color = “Black”, Age = 1 } );
And now with the collection initializer:
List<animal> animals = new List<animal> {
new animal { Color = “Brown”, Age = 2 },
new animal { Color = “Black”, Age = 1 }
}
No comments:
Post a Comment