Thursday, October 1, 2009

You can do *what* with an Auto Property?

I hate auto properties.  You know, these things:

public string UserName { get; set; }

That’s right, I can’t stand the fact that the language makes it so easy for me to break encapsulation on my objects.  I find it insulting that .NET thinks I would rather save a few character strokes on the keyboard than actually follow the most basic of object-oriented principles.

Until now…

I have this property on an object:

public string UserName { get { return _userName; } }

I was a little curious today when I looked at my read-only property (because all of my properties are read-only) and I noticed that ReSharper had put a barely noticeable little green line under the first two letters of the  property name.  I’d seen this little green line before, but ignored it every time.  I was a little curious what it thought I could to do make this code better, so I hovered my mouse over it and was a little surprised to see it suggest that I should convert it to an auto property.  I mean, seriously ReSharper, there is no way that I’m going to convert that into an auto property because auto properties require a setter and setters are just plain evil!  Ok, I get the irony in linking to that article since it says setters and getters are evil, but I’m willing to ignore that for now if you are.

Anyway, ReSharper thought I should use an auto property and I was steadfast against it, but I was curious.  I’ve been using ReSharper for a few years and I accept nearly all of the suggestions it makes, but this one was getting the better of me.  I was all ready to go on a big rant when I accepted the suggestion and ReSharper just went ahead and added the setter for me…but it didn’t…well…not really…at least not how I expected it to.  This is what it did:

public string UserName { get; private set; }

A private setter!  Why didn't I think of that?!  Alright, you already knew that, this is no big deal to you, that’s OK.  This is one of those little language features that, for whatever reason, I had never stumbled across before.  It’s a small change, but I like it.  I think I’ll accept that suggestion, thanks ReSharper.

No comments: