Home > .NET 3.5, C# 3.0 > Making Automatic Properties Read Only

Making Automatic Properties Read Only

November 28, 2007

In yesterday’s post, I included a blurb about Automatic Properties. Today, in my weekly C# class at my company, I was showing Automatic Properties to my students and I mentioned that you could not have a Read Only automatic property. To prove this, I removed the Setter from like so:

// This will not compile
public string FirstName { get; }

I then received a Compile error indicating that an Automatic Property must have both a getter and a setter. I was about to say that this proved my point when it dawned on me that I could try making the setter private, like so:

// Look, a Read Only Automatic Property!
public string FirstName { get; private set; }

Now this compiles just fine. I swear that at VSLive I saw someone try this and it failed, so either my memory is faulty or this was corrected before VS2008 went RTM. In either case, you can now implement an Automatic Property with a private Setter.

In my book, this is not truly Read Only, since the value can still be changed internally, but at least external consumers of the Property will not be able to alter its value, so I’ll still consider this a way to have a Read Only Automatic Property.

Advertisements
Categories: .NET 3.5, C# 3.0
%d bloggers like this: