C# Object and collection initializers


What is Object Initializer?

          Object initializers provide a way to assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor.

First create Employee class


namespace ObjectInitialzer
{

    public class Employee
    {      
        #region private Variable
        private int _employeeID;
        private string _employeeName;
        #endregion

        #region public variable
        public int EmployeeID
        {
            get
            {
                return _employeeID;
            }
            set
            {
                _employeeID = value;
            }
        }
        public string EmployeeName
        {
            get
            {
                return _employeeName;
            }
            set
            {
                _employeeName = value;
            }
        }
        #endregion

        public Employee()
        {
        }
    }

}
      If I want to access  EmployeeID  and EmployeeName from Employee class first I need to create a new instance of Employee class. Sea bellow code

namespace ObjectInitialzer
{
    public class Customer
    {
        public Customer()
        {
            Employee objEmployee = new Employee();
            objEmployee.EmployeeID = 1;
            objEmployee.EmployeeName = "John";
        }
    }
}
We accive the same this using Object Initialization Expressions in C#3.0 Features to create an Employee as follows       

namespace ObjectInitialzer
{
   static void Main(string[] args)
   {
      Customer obj = new Customer();
   }

    public class Customer
    {
        Employee obj = new Employee { EmployeeID = 1, EmployeeName = "john" };
    }
}

Collection Initialization Expressions
          Collection Initializers are similar in concept to Object Initializers.  They allow you to create and initialize a collection in one step.  By using a collection initializer you do not have to specify multiple calls to the Add method of the class in your source code; the compiler adds the calls.

namespace ObjectInitialzer
{
   static void Main(string[] args)
   {
      Customer obj = new Customer();
   }

    public class Customer
    {
        List<Employee> obj = new List<Employee>
        {
            new Employee{EmployeeID=1,EmployeeName="john"},
            new Employee{EmployeeID=2,EmployeeName="Raj"}
        };
    }
}

No comments:

Post a Comment