C# 3.0 Feature - Object Initialization Expressions - C# 3.0 Examples and Tutorials

C# 3.0 Feature - Object Initialization Expressions - C# 3.0 Examples and Tutorials

by David Hayden ( ASP.NET C# SQL Server Developer ), Filed: C# 3.0 Examples and Tutorials

 

I have talked about two other C# 3.0 Features thus far:

Another interesting feature that will seem more valuable once I mention anonymous types is Object Initialization Expressions.

 

Object Initialization Expressions

Object Initialization Expressions allow us to initialize an object without invoking its constructor and setting its properties.

If you take a simple customer class as follows:

 

public class Customer
{
    private int _id;
    public int Id
    {
        get { return _id; }
        set { _id = value; }
    }
    
    private string _name;
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
    
    private string _city;
    public string City
    {
        get { return _city; }
        set { _city = value; }
    }

    public Customer() {}

}

 

You can use Object Initialization Expressions in C# 3.0 to create a customer as follows:

 

Customer customer = new Customer{ Id = 1, Name="Dave",
City
= "Sarasota" };

 

No where in the code above do we invoke a constructor or set any properties directly. The code above is equivalent to the following code:

 

Customer customer = new Customer();
customer.Id = 1;
customer.Name = "Dave";
customer.City = "Sarasota";

 

You can create a list of customers as follows using Object Initialization Expressions in C# 3.0:

 

List<Customer> listOfCustomers =
        new List<Customer> {
            { Id = 1, Name="Dave", City="Sarasota" },
            { Id = 2, Name="John", City="Tampa" },
            { Id = 3, Name="Abe", City="Miami" }
        };

 

Conclusion

A lot of these new C# 3.0 features, like Extension Methods, Lambda Expressions, and now Object Initialization Expressions, are necessary for LINQ related functionality and are cool in their own right.

News Feed: David Hayden ( ASP.NET C# SQL Server Developer )

Filed: C# 3.0 Examples and Tutorials

 

posted on Monday, December 04, 2006 8:02 PM

My Links

Post Categories

Article Categories

Archives

Loose-Leaf Tea