Second Stanza

August 23, 2008

Object Initializers and Read Only Properties

Filed under: .NET Development — Tags: — dfbaskin @ 8:07 pm

Auto-implemented properties save you some coding as well as using using object initializers. Here is an example of the syntax (from the previous link):

private class Cat
{
    // Auto-implemented properties
    public int Age { get; set; }
    public string Name { get; set; }
}

static void MethodA()
{
    // Object initializer
    Cat cat = new Cat { Age = 10, Name = "Sylvester" };
}

What about when you want to create immutable classes? Using the “private set;” syntax on an auto-implemented property does not allow you to use the object initializers syntax to set the read-only property. This requires creating a special constructor for this purpose.

This thread contains an interesting discussion of these issues.

Create a free website or blog at WordPress.com.