Mixing Accessibility for Class Properties

By Michael Flanakin @ 6:51 AM :: 1598 Views :: .NET :: Digg it!

I’m sure just about all of us have happened upon a scenario where we needed to have a property read-only to consumers, but writable by child classes. Well, maybe it’s not something you run into every day, but I know I’ve run into it at least a dozen times since I picked up .NET when it was first released. The practice I’ve seen most often is a developer will create a public property and a protected method to set the field.

public class User
{
    private int _id;
    public int Id
    {
        get { return this._id; }
    }
    protected void SetId(int id)
    {
        this._id = id;
    }
}

Sure, this works. Nobody will really question it, but I don’t like it. I’ve always wanted the ability to use a property for that; not just any property, but the same one used to get the value. I was explaining my complaint to a coworker, Don Hurley, and, in the middle of that conversation, thought up with an ingenious way to implement such a feature.

public class User
{
    private int _id;
    public int Id
    {
        get { return this._id; }
        protected set { this._id = value; }
    }
}

Simply add the desired access modifier to the getter or setter, depending on which you want to be less accessible. Sure, you could probably decorate the more accessible getter/setter, but that seems backwards. Maybe it’s just me. Either way, I thought this was probably the best way to solve the problem. I’m so smart… or so I thought ;-)

The next day, I got an email from Don. Despite the fact that he asked me never to talk to him about something on a Friday afternoon that’ll keep the gears running on Saturday morning, he had some news... it works! I read the email a second time to make sure I wasn’t misunderstanding him. In disbelief, I replied asking, “Are you saying this works!?” You ask a stupid question… “I wouldn’t have sent it if it didn’t,” he answered. Umm… good point.

Don is officially my hero of the week. I have no idea why I never thought to try this. Then again, I did just think of it. Apparently, tho, I’m not the only one. I am somewhat curious as to how long this has been in the language. For now, I’ll just take advantage of it and spread the word. This is one of those great hidden gems that I love about C#.

Ratings