C# 3.0 Features. Part II: Object and Collection Initialization
Previous materials of C# 3.0 Feature series:
Object Initialization
New object initialization technique gives us ability to define and fill the public property of the object on the fly. This expression was created to support LINQ but it can be used anywhere. This expression helps to fill values during the initialization and keep constructor empty.
1: public enum Sex { Male, Female }
2:
3: public class User
4: {
5: public int UserId { get; private set; }
6: public string UserName { get; set; }
7: public string UserAddress { get; set; }
8: public DateTime DateOfBirth { get; set; }
9: public Sex UserSex { get; set; }
10: }
User object initialization by using OLD style expression:
1: User user = new User();
2: user.UserAddress = "FR, Paris";
3: user.DateOfBirth = new DateTime(1984, 1, 1);
4: user.UserName = "Michelle";
5: user.UserSex = Sex.Female;
Similar object initialization by using new feature:
1: User user = new User
2: {
3: UserAddress = "US,Redmond",
4: DateOfBirth = new DateTime(1974, 1, 1),
5: UserName = "Mike",
6: UserSex = Sex.Male
7: };
Collection Initialization
There is a similar feature for collection initialization. We can define a collection and add object on the fly.
The standard way of collection initialization:
1: List<User> users = new List<User>();
2: users.Add(user1);
3: users.Add(user2);
Initialization of collection by using new C# 3.0 feature:
1: List<User> users = new List<User>{user1, user2};
Both in one
Finally we can combine those two expressions and have the whole collection initialization in one line. This could be helpful when preparing collection with dummy data for testing.
1: List<User> users = new List<User>
2: {
3: new User
4: {
5: UserAddress = "US,Redmond",
6: DateOfBirth = new DateTime(1974, 1, 1),
7: UserName = "Mike",
8: UserSex = Sex.Male
9: },
10: new User
11: {
12: UserAddress = "US, New-York",
13: DateOfBirth = new DateTime(1978, 1, 1),
14: UserName = "David",
15: UserSex = Sex.Male
16: }
17: };