Sure, everyone talks about Generics, Anonymous methods, Covariance and Contravariance. It’s all you hear about, practically. And don’t get me wrong; I love those features just as much as the next person. However, one of my favorite new features is hardly getting any press at all. You can now have different accessibility levels for your setters and getters for properties. Huh? Why would I want that? Well, consider the following:
Ø You have a class with a field with some complex set logic.
Ø Obviously, you want all modifications to the property to go through your setter, so you make the field private.
Ø You want this property to be read-only externally, but writable to classes that inherit from your class as long as the subclasses go through your setter.
In the past, there just wasn’t a way to do this. You ended up having to make the setter public, or re-write your set code in your inherited class or provide a protected method to handle this logic. To all three methods I say, “ugh.” But now, it’s very simple.
public class Foo
{
private string _name;
public string Name
{
get { return _name; }
protected set { _name = value; }
}
}
Woohoo! Ok, so the simple things excite me.