Object creation - What's new in .net 3.5?

.net 3.5 allows you to set the object's properties during initialization. Prior to .net 3.5, we used create parametrized constructors and in set the property values inside the constructors as below.


namespace My_Samples
{
    public class MyClass
    {
        public MyClass(string firstName, string lastName)
        {
            FirstName = firstName;
            LastName = lastName;
        }

        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

And you will initialize the object as


MyClass obj1 = new MyClass("MyFirstName", "MyLastName");

Now we have more cleaner way of doing this in .net 3.5.


namespace My_Samples
{
    public class MyClass
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

Notice that there is no constructor this time. And you will initialize the object as below.


MyClass obj = new MyClass() { FirstName = "MyFirstName", LastName = "MyLastName" };

Pretty Neat...
Keep coding…

No comments:

Post a Comment