Home .NET New Attributes in .NET 4

New Attributes in .NET 4

by admin

Introducing two new attributes that will improve productivity by reducing the amount of code :

  • [Optional]
  • [DefaultParameterValue]

I’m sure almost all of you have the following code in your projects :

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;
}
* This source code was highlighted with Source Code Highlighter

And there’s nothing wrong with that, but I think three constructors looks ugly in this case. I would prefer to have one. But what if we suddenly want to change the default value of whatever ? And we have two places in our code where it’s used that we have to change-a rather inconvenient action.
But with the new attributes, we can only have one constructor.

public class Thingy
{
public Thingy([ Optional , DefaultParameterValue ( "Default" )] string name,
[ Optional , DefaultParameterValue (-1)] int whatever)
{
}
}
* This source code was highlighted with Source Code Highlighter

Now the code looks much better, don’t you agree? My default values are in one place, and I have one constructor instead of three. This method works with normal methods as well.
And yes, you don’t have to use attributes, you can implement everything in another, again, new way.

public class Thingy2
{
string n;
int i;
public Thingy2( string name = «Default», int whatever = -1)
{
n = name;
i = whatever;
}
}
* This source code was highlighted with Source Code Highlighter

You may also like