I’ve decided to start a series of C# 3.0+ features that every dev should know about.  Probably I’m preaching to the choir (and I’m certainly not the only person mentioning these), but it’s easy to get used to features from

 

Automatic properties

This is such a simple feature, but a nice one to know about.  Good object-oriented design demands that you never expose class fields directly.  Why not?  It’s all a matter of control!  Who wants to take a chance that other code might invalidate your values?  A name field set to null, or an age field set to a negative value.  Properties allow you to control what values can be set, but can also be used to notify listeners of a new value, to trigger a background action, or even to restrict a field to be read-only.  The problem, is that the code to expose fields as properties is fairly boilerplate most of the time.  You can use the Refactor menu (right-click on a field) to create this boilerplate code, but it generates it right after the property, which annoys me (I always move them down to a special Properties block in my code).  So the fastest way of generating basic properties, is using the Automatic Properties feature.  This doesn’t let you enforce any logic (blocking NULL values or negative numbers), but it gets your code started right.  Especially when you are initially mocking up classes, this is a great feature to use:

public property string FirstName
{
    get;   set;
}

 

This looks similar to an interface definition, but this is real implementation.  You now have a public property that is both gettable and settable.  There’s no backing variable.  In the class code, just use the public property.  Later on, if you need to enforce validation, initialization, event raising, etc. you can add the backing variable and create custom get/set blocks without changing your public interface.  Perfect!