Welcome to MSDN Blogs Sign in | Join | Help

UK Application Development Consulting

Your dev. Our passion.
New .NET Attributes

The very first talk I gave on .NET was on custom attributes – some time way back in late 2000 or early 2001. At the time I was espousing the benefits of using custom attributes to add on details of unit tests and bug fixes.

There have been many additions to .NET since then and I spied a couple of *really* cool new attributes in .NET 4 the other day so had to share them.

Enter (drum roll please) :-

  • [Optional]
  • [DefaultParameterValue]

Yay!

These are (I believe) a real productivity boost, and will make your code much easier to read. I bet you have some code like the following hanging around, don’t you…

public class Thingy
{
    public Thingy()
        : this("Default", -1)
    {
    }

    public Thingy(string name)
        : this(name, -1)
    {
    }

    public Thingy(string name, int whatever)
    {
        _name = name;
        _whatever = whatever;
    }

    // Other code...

    private string _name;
    private int _whatever;
}
Now there’s nothing desperately wrong with this, although I feel
that 3 constructors is a bit ugly, I’d rather just have one. And
what if I want to change the default value for the ‘whatever’ value
– there are two places it’s used in the code above and I’d need to
update both which is a bit on the fragile side.

With these swanky new attributes I can have just the one constructor…

public class Thingy
{
    public Thingy([Optional, DefaultParameterValue("Default")] string name,
                  [Optional, DefaultParameterValue(-1)]int whatever)
    {
    }
}

Now that’s a whole lot better if you ask me! My defaults are in one place, I have only one constructor rather than three (obviously this works on methods too), and Intellisense and the C# environment understand the [Optional] attribute and present the appropriate stuff to me.

Now as if that wasn’t enough we’ve updated C# to support this without even having to write attributes (thanks to Wes Haggard for pointing this out to me)…

public class Thingy
{
    public Thingy(string name = "Default",
                  int whatever = -1)
    {
    }
}

Ooh, how cool is that? All in all I’m very happy with this little addition to .NET and C#.

Originally posted by Morgan Skinner on 05 August 2009 here.

Posted: Thursday, October 22, 2009 10:00 AM by ukadc
Filed under: , ,

Comments

No Comments

Leave a Comment

(required) 

(required) 

(optional)

(required) 

  
Enter Code Here: Required

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker