Sunday, May 26, 2013

Object Initializers in c#.net


Object Initializers with Autoimpeleted Properties
Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor. The following example shows how to use an object initializer with a named type, Student. Note the use of auto-implemented properties in the Student class.
class Student
{
    ///these are auto-implemented properties
    public string Name { get; set; }
    public int Standard { get; set; }
    public int  Age { get; set; }

}

Student objstudent = new Student {Name = “Bharathi”, Standard =3, Age=7};

var studentInfos =
    from s in students
    select new { s. Name, s.Standard ,s.Age};
 
 
 
When this query is executed, the studentInfos  variable will contain a sequence of objects that can be accessed in a foreach statement as shown in this example:
 
foreach(var s in studentInfos)
{
   Console.writeline(“Student Name “+s.Name);
   Console.writeline(“Student Age “+p.Age);
 
}
 
 
select new {S.Name, StudentAge = S.Age};
 
Collection Initializers :
 
Collection initializers let you specify one or more element initializers when you initialize a collection class that implements IEnumerable. The element initializers can be a simple value, an expression or an object initializer. 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.
 
// The following code consolidates examples from the topic. 
class ObjInitializers
{
    class Student
    {
        // Auto-implemented properties. 
        public int Age { get; set; }
        public string Name { get; set; }
    }
 
    static void Main()
    {
        Student student = new Student {Age = 10, Name = "Akarsh" };
 
        List< Student > students = new List< Student >
        {
            new Student (){ Name = "Anish", Age=8 },
            new Student (){ Name = "Akarsh", Age=2 },
            new Student (){ Name = "Raja", Age=14 }
        };
 
 
 
        List< Student > moreStudents = new List< Student >
        {
            new Student (){ Name = "Akarsh", Age=5 },
            new Student (){ Name = "Anish", Age=4 },
            null
        };
 
        // Display results.
        System.Console.WriteLine(Student.Name);
 
        foreach (stud s in Student)
            System.Console.WriteLine(s.Name);
 
        foreach (stud s in Students)
            if (s != null)
                System.Console.WriteLine(s.Name);
            else
                System.Console.WriteLine("List element has null value.");
    }
}


Although object initializers can be used in any context, they are especially useful in LINQ query expressions. Query expressions make frequent use of anonymous types, which can only be initialized by using an object initializer, as shown in the following declaration.
var objStudent = new { Name = “Bharathi”, Standard =3, Age=7 };
Anonymous types enable the select clause in a LINQ query expression to transform objects of the original sequence into objects whose value and shape may differ from the original. This is useful if you want to store only a part of the information from each object in a sequence. In the following example, assume that a students object (s) contains many fields and methods, and that you are only interested in creating a sequence of objects that contain the student name and the Age.

Each object in the new anonymous type has two public properties which receive the same names as the properties or fields in the original object. You can also rename a field when you are creating an anonymous type; the following example renames the StudentAge field to StudentAge.

No comments:

Post a Comment