19 mai 2026

nameof() du C#6

Parmis les nouveautés qui arrivent avec C#6 du Framework 4.6, voici nameof()

nameof()

Cette expression est utilisée pour retourner le nom d’une variable. Ca va pouvoir être bien utile dans notre système de log d’erreurs par exemple !

[cc lang= »csharp » escaped= »true » width= »400″ nowrap= »0″ line_numbers= »0″ theme= »vsdark »]

var mystring = « maison »;
Console.WriteLine (nameof(mystring));

//retournera : mystring
[/cc]

On va aussi éviter de passer en dur certaines chaines de caractères :

avant C#6

[cc lang= »csharp » escaped= »true » width= »500″ nowrap= »0″ line_numbers= »0″ theme= »vsdark »]
private bool _checking;
public bool Checking
{
get { return this._checking; }
set
{
this._checking = value;
this.OnPropertyChanged(« Checking »);
}
}
[/cc]

Dès C#6

[cc lang= »csharp » escaped= »true » width= »500″ nowrap= »0″ line_numbers= »0″ theme= »vsdark »]
private bool _checking;
public bool Checking
{
get { return this._checking; }
set
{
this._checking = value;
this.OnPropertyChanged(nameof(Checking));
}
}
[/cc]

Laisser un commentaire