Many times in code we need to write the name of class member. Usually while throwing validation exceptions from server or firing PropertyChanged events in case of 2 way bindings. C# 6.0 introduces nameOf expression
e.g.
public void OldWay(string firstName , string lastName)
{
if (firstName != null) throw new Exception(string.Format("{0} is required", "firstName"));
if (lastName != null) throw new Exception(string.Format("{0} is required", "lastName"));
}
public void NewWay(string firstName, string lastName)
{
if (firstName != null) throw new Exception(string.Format("{0} is required", nameof(firstName)));
if (lastName != null) throw new Exception(string.Format("{0} is required", nameof(lastName)));
}
More Example where this can be handy:
class Person : INotifyPropertyChanged
{
int _personId;
public int PersonId {
get { return _personId; }
set {
_personId = value;
//Old way
// OnPropertyChanged("PersonId");
//New
OnPropertyChanged(nameof(PersonId));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Using this keywords helps cleaning up code by removing literals in code.
Declaring out parameter during method call
Time and again micsrosoft has come up with syntaxes that have been used for brevity. One handy addition is removing the need for declaring out parmeter before actually using it.
public bool TryParseInt(string value)
{
if (int.TryParse(value, out int parsedvalue))
{
return true;
}
return false;
}