DCSIMG
Object Initializers in C# 3.0 - Maor's Blog

Object Initializers in C# 3.0

C# 3.0 includes a new language feature called object initializers.

Object initializers enable you to initialize the state of an object with a single expression that does not require use of parameterized constructors.

Basically, this feature allows you to initialize an object by both creating the object instance (i.e. a new expression) as well as assign values to one or more properties in a single sentence, or to initialize a collection with a set of values to add to it in a single expression.

    class Program
    {
        static void Main(string[] args)
        {
            Customer cus1 = new Customer() { Name = "Maor", City = "Herzliya" };
            Customer cus2 = new Customer() { Name = "Guy", City = "Ramat Hasharon" };

            List<Customer> customers = new List<Customer>() { cus1, cus2 };

        }
    }

    class Customer
    {
        public string Name { get; set; }
        public string City { get; set; }

    }

The first & the second lines initialize a Customer object with the default constructor (though you could call a constructor with parameters here), and assigns explicit values to the Name and City properties.

The third line initializes a collection of type List<Customer> with the objects cus1 and cus2.

 

 

Technorati Tags:

del.icio.us Tags:

Published 05 September 2007 12:51 AM by Maor David-Pur

Comments

# Maor David - The Blog said on 27 September, 2007 09:27 AM

How many times have you written wrapper methods for objects that in reality you wished were part of the

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above:

Search

Go

This Blog

News

    RSS

     

    Connect with Me

    Maor's Facebook profile  Follow Maor on Twitter  Maor's profile on Linkedin  Maor in FriendFeed 
           

Syndication