Wednesday, June 25, 2008

Automatic properties

With the new automatic properties added in the .NET 3.5 C# compiler you can now add a nice property as follows:

public string Name { get; set; }

But can you add read-only or write-only properties this way. Not on your nelly! Try adding only a get (or indeed a set) accessor as follows:

public string Name { get; }

And you get a compiler error – you must implement both the get and set accessors for automatic properties. Why I ask you? Why!?!

UPDATE (26/01/2010) - so looking back on this 18 months later it makes perfect sense. What a fool! How the hell do you set the value of something that you can't set? Doh!

No comments: