In this article, I will talk about Object and Collection Initializers in C# 3.0.
Object initializers let us assign values to any accessible fields or properties of an object at the time of creation without having to explicitly invoke a constructor.
When using .Net 2.0, to initialize an instance of a User, we would (1) either overload the constructors, (2) or create an instance first and assign values accordingly.
Object initializers let us assign values to any accessible fields or properties of an object at the time of creation without having to explicitly invoke a constructor.
When using .Net 2.0, to initialize an instance of a User, we would (1) either overload the constructors, (2) or create an instance first and assign values accordingly.
User oldUser = new User();
oldUser.UserId = "OUSR";oldUser.UserName = "Old User";oldUser.UserEmail = "old.user@somewhere.com";oldUser.UserLevel = 3;
Now, with C# 3.0 and .NET 3.5, we will be able to initialize the object by creating the instance and assigning the values to the properties in a single statement. Using this new syntax, the code will look like:
User test = new User { UserId = "NUSR", UserName = "New User",
UserEmail = "new.user@anywhere.com", UserLevel = 3};Similarly, if we had to create a list of users in .NET 2.0, we would first create the list and then add the users one by one.
User oldUser = new User();
oldUser.UserId = "OUSR";oldUser.UserName = "Old User";oldUser.UserEmail = "old.user@somewhere.com";oldUser.UserLevel = 5;
User newIser = new User();
newIser.UserId = "NUSR";newIser.UserName = "New User";newIser.UserEmail = "new.user@anywhere.com";newIser.UserLevel = 3;
List<User> users = new List<User>();
users.Add(oldUser);
users.Add(newIser);
And now, with C# 3.0 and .NET 3.5, this can be achieved in just one single statement:
List<User> users = new List<User> {
new User { UserId = "OUSR", UserName = "Old User",
UserEmail = "old.user@somewhere.com", UserLevel = 5},new User { UserId = "NUSR", UserName = "New User",
UserEmail = "new.user@anywhere.com", UserLevel = 3}};

0 comments:
Post a Comment