24 avril 2024

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 !

var mystring = "maison";
Console.WriteLine (nameof(mystring));

//retournera : mystring

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

avant C#6

private bool _checking;
public bool Checking
{
    get {  return this._checking; }
    set
    {
        this._checking = value;
        this.OnPropertyChanged("Checking");
    }
}

Dès C#6

private bool _checking;
public bool Checking
{
    get {  return this._checking; }
    set
    {
        this._checking = value;
        this.OnPropertyChanged(nameof(Checking));
    }
}

Laisser un commentaire