Friday, 1 April 2016

Avoid using magic string use Nameof operator instead

Avoid using magic string use Nameof operator instead
There are several occasions when you will need to use “magic string” within your code. Such “magic strings” are normal C# strings that map to program elements within your code. For example, when raising OnPropertyChanged event, you’d use a string for the name of the corresponding property. Unfortunately, these magic strings had no compile time validation and any program element changes (such as renaming property) wouldn’t automatically update the magic string, resulting in an inconsistency that was never caught by the compiler.

Extracting the Property Name with a Nameof Expression

public string FirstName
{
            get { return _firstName; }
            set { _firstName = value; OnPropertyChanged(nameof(FirstName)); }
}


There are several other occasions where you can avoid the writing magic string in you code.