Saturday, December 13, 2014

What is object and Collection initializers c#?

C# 3.0 provides the various features one of them object and collection intializer. This means that you assign the values to any accessible field or properties of object at creation time without having to invoke a constructor followed by lines of assignment statements. Here are example object and collection initializers
Suppose we have class named “Employee
public class Employee
    {
        public int id { get; set; }
        public string Name { get; set; }
        public bool IsActive { get; set; }
        public string Address { get; set; }
        public decimal Salary { get; set; }
    }

Employee emp= new Employee{Name="test",id=1,Address="ddf", IsActive=true,Salary=44 };
In c# 2.0 you have to declare as code given below
   Employee emp = new Employee();
            emp.Name = "test";
            emp.id = 1;
            emp.Address = "ddf";
            emp.IsActive = true;
            emp.Salary = 44;

So c# 3.0 minimizes your code and time. Similar collection initialize in c# 3.0 as example given below

   List<Employee> emp = new List<Employee>
        {
            new Employee(){id=1,  Name = "Neel", Salary=8, IsActive= true,Address="Usa" },
            new Employee(){id=2, Name = "Sharma", Salary=2 , IsActive= false,Address="India"  },
            new Employee(){id=3, Name = "Trick", Salary=14,  IsActive= true,Address="UK"  }
        };

No comments:

Post a Comment

http://blogsiteslist.com