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.

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at

%d bloggers like this: