Sunday, 11 March 2012

What is Object Initialization it is useful?

Yes, till now we preparing the object then we passing the values to object through Properties. but C# 3.0 onwords we can directly assign values to object while initialization without parametrized Consturctor of that type. is called Object Initialization.
Ex:

class Book
    {
        public string Name { get; set; }
        public string Author { get; set; }
        public Publications Publish { get; set; }
        public DateTime Date { get; set; }
 
    }

class Publications
    {
        public string Publish { get; set; }
    }
till now the old way is
                Book bobj1 = new Book();

            //  bobj1.Name = "Interview questions";
          //  bobj1.Author = "pkb";   ----> old style of object intializaton

we prepared 2 types those are Book and Publications.
now Initialization.



            Book bobj1 = new Book { Name = "Interview Questions", Author = "pkb" };
            bobj1.Date = DateTime.Now;
            bobj1.Publish = new Publications { Publish = "BPB PUBLICATIONS" };
       
            Console.WriteLine(bobj1.Name);
            Console.WriteLine(bobj1.Author);
            Console.WriteLine(bobj1.Date);
            Console.WriteLine(bobj1.Publish.Publish);
           then we can seen second way style inside book initialization only of publication also.
            Console.WriteLine("=====second way==");
            Book bobj2 = new Book
            {
                Name = "Design Patterns",
                Author = "kasi",
                Date = DateTime.Now,
                Publish = new Publications { Publish = "SriSai Publications" }
            };
            Console.WriteLine(bobj2.Name);
            Console.WriteLine(bobj2.Author);
            Console.WriteLine(bobj2.Date);
            Console.WriteLine(bobj2.Publish.Publish);
this is the good readablity.
Advantage: is in runtime creates the fields for those intialized properties; 
And no need to Pass all the Properties at a time if we pass 2 or 3 or how many object is initialize for those values only object is initialized.
Note : [incase of constructor we need pass as per constructor signature]
Ex: 
 Book bobj1 = new Book { Name = "Interview Questions" };   //  bobj1 with 1 value of object
 Book bobj1 = new Book { Name = "Interview Questions", Author = "pkb" };  bobj1 with 2 values
 Book bobj1 = new Book { Name = "Interview Questions", Author = "pkb",Date=DateTime.Now };
bobj1 with 3 Values.
so memory will be save and programmer will be take as per his need of values


No comments:

Post a Comment