Welcome to SpellCoder Sign in | Join | Help

C# 3.0 Properties Acessor Tips

If you are familiar with C# 3.0, you would already noticed the new shortcut for defining a property without the need to declare the variable behind the property, so for creating a property called Length, all what you have to do is write it like this.

public int Length { get; set; }

 

This is cool as most of our classes contains bunch of properties and this saves sometimes and also it makes the intellisence list of members much shorter, but this is not the whole thing, what if you want to declare a property with a private setter and public getter?

Here comes a cool part :)

public int Length { get; private set; }

 

Now the Set operation is only accessible inside the class, you can also do stuff like protected, internal for either the set and get, or even remove one of them.

I know that this post sounds a bit old, but I felt it funny when I read the private keyword at the middle of the line :)

Published Friday, January 11, 2008 7:57 PM by Mohammed Hossam
Filed Under: ,

Comments

# re: C# 3.0 Properties Acessor Tips

Saturday, January 12, 2008 2:33 AM by Cyril Gupta
One thing you can't do with automatic properties is have readonly properties. That could have helped too, don't you think?

Maybe they didn't do it because they wanted to avoid confusion, after all a readonly property is supposed to readonly only if it's accessed from a location outside the containing class. Inside it, it should not be readonly.

Nevertheless, I would have liked if there was facility to mark the property readonly for outside code.

# re: C# 3.0 Properties Acessor Tips

Saturday, January 12, 2008 9:10 AM by Fady
nice tip ;)

# re: C# 3.0 Properties Acessor Tips

Saturday, January 12, 2008 2:00 PM by Frank Quednau
Sorry, but in this case you cannot remove one of them. The compiler will tell you that you "...must declare a body because it is not marked abstract or extern. Automatically implemented properties must define both get and set accessors."

If you think about it, it is unavoidable, otherwise you wouldn't have a chance to either set it in any way, or read it in any way.

"get, private set" essentially has the effect of a read-only property from the outside. Initializing at construction can still be done nicely with the "readonly" keyword.

# re: C# 3.0 Properties Acessor Tips

Sunday, January 13, 2008 4:48 AM by Amir Magdy
nice 1
Anonymous comments are disabled