📜 ⬆️ ⬇️

New Attributes in .NET 4

I present to you two new attributes that will improve productivity, by reducing the amount of code:


I am sure that almost each of you has the following code in the 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 is nothing terrible in this, but I believe that the three designers in this case look ugly. I would prefer to have one. But what if we suddenly want to change the default value of the variable whatever ? But we have two places in the code where it is used, which we will have to change - a rather inconvenient action.

But with new attributes, we can have only 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, agree? My default values ​​are in one place, and I have one constructor, not three. This method works with conventional methods.

And yes, it is not necessary to use attributes, you can implement everything in another way, again, in a 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 .

')

Source: https://habr.com/ru/post/66331/


All Articles