Auto-property initializers

The next release of C# 6 has some amazing new features. In a series of blog posts I will cover some of them.

At first auto-property initializers does not sound very interesting at all, but wait…

Simple things as setting a default value for a property.

public class Order
{
  public int OrderNo { get; set; } = 1;
}

Or using the getter-only auto-property which are implicit declared readonly and can therefore be set in the constructor.

public class Order
{
  public Order(int orderNo)
  {
    OrderNo = orderNo;
  }
  
  public int OrderNo { get; }
}

From my point of view the value of auto-properties comes to shine when used with list properties where the list has to be initialized.

public class Order
{
  public IEnumerable<OrderLine> Lines { get; } = new List<OrderLine>();
}

I often forget to initialize a list property in the constructor and therefor get a NullReferenceException when accessing the list property. Now I might even be able to omit the constructor all together.

Expression-bodied methods

The next release of C# 6 has some amazing new features. In a series of blog posts I will cover some of them.

Expression-bodied methods make it possible for methods and properties to be used as expressions instead of statement blocks, just like lambda functions.

Let’s revisit the Person.ToString method in the Awesome string formatting blog post.

public class Person
{
  public string Name { get; set; }

  public Address HomeAddress { get; set; }

  public override string ToString()
  {
    return string.Format("{Name} lives in {HomeAddress?.City ?? "City unknown"}.");
  }
}

The ToString method can be written as a lambda function.

public override string ToString() => string.Format("{Name} lives in {HomeAddress?.City ?? "City unknown"}.");

And simplified with String interpolation.

public override string ToString() => $"{Name} lives in {HomeAddress?.City ?? "City unknown"}.

Use expression-bodied methods anywhere…

public Point Move(int dx, int dy) => new Point(x + dx, y + dy);
public static Complex operator +(Complex a, Complex b) => a.Add(b);
public static implicit operator string (Person p) => "\{p.First} \{p.Last}";

Awesome string formatting

The next release of C# 6 has some amazing new features. In a series of blog posts I will cover some of them.

Using the versatile string.Format required a lot of typing and keeping the numbed placeholders in sync with the method parameters.

var numerator = 1;
var denominator = 2;

Console.WriteLine("Fraction {0}/{1}", numerator, denominator);

// Output:
//   Fraction 1/2

In C# 6 is it a lot easier with String interpolation:

var numerator = 1;
var denominator = 2;

Console.WriteLine("Fraction {numerator}/{denominator}");

// Output:
//   Fraction 1/2

Referencing the variable, property or field directly within the string. It is even possible to access properties or use expressions.

public class Person
{
  public string Name { get; set; }
  public Address HomeAddress { get; set; }

  public override string ToString()
  {
    return string.Format("{Name} lives in {HomeAddress.City}.");
  }
}

The string.Format is not event needed, but use the shorthand notation $.

return $("{Name} lives in {HomeAddress.City}.";

This is easily combinable with an expression and the null-conditional operator (?.) operator.

return $"{Name} lives in {HomeAddress?.City ?? "City unknown"}.";

The nameof operator

The next release of C# 6 has some amazing new features. In a series of blog posts I will cover some of them.

The nameof operator takes a class, method, property, field or variable and returns the string literal.

var p = new Person();

Console.WriteLine(nameof(Person));
Console.WriteLine(nameof(p));
Console.WriteLine(nameof(Person.Name));
Console.WriteLine(nameof(Person.HomeAddress));

// Output:
//   Person
//   p
//   Name
//   HomeAddress

This is handy when doing input validation by keeping the method parameter and the parameter name of the ArgumentNullException in sync.

public Point AddPoint(Point point)
{
  if (point == null)
    throw new ArgumentNullException(nameof(point));
}

The nameof operator is useful when implementing the INotifyPropertyChanged interface

public string Name
{
  get
  {
    return _name;
  }
  set
  {
    _name = value;
    this.OnPropertyChanged(nameof(Name));
  }
}

The Chained null checks blog post shows how to simplify triggering event in the OnPropertyChanged with the null-conditional operator.

Chained null checks

The next release of C# 6 has some amazing new features. In a series of blog posts I will cover some of them.

Null-conditional operators is one of the features in C# 6 that will save the world from a lot of boilerplate code and a bunch of NullReferenceExceptions. It works as chained null checks!

Console.WriteLine(person?.HomeAddress?.City ?? "City unknown");

Note the null-conditional operator (?.) after person and HomeAddress, it returns null and terminates the object reference chain, if one of the references are null.

It is the same logic as the below code that you can use today.

if (person != null)
    person.HomeAddress != null)
{
  Console.WriteLine(person.HomeAddress.City);
}
else
{
  Console.WriteLine("City unknown");
}

The null-conditional operator will also make it easier to trigger events. Today it is required to reference the event, check if it is null before raising the event like so.

protected void OnPropertyChanged(string name)
{
  PropertyChangedEventHandler handler = PropertyChanged;

  if (handler != null)
  {
    handler(this, new PropertyChangedEventArgs(name));
  }
}

But the null-conditional operator provides a tread-safe way of checking for null before triggering the event.

PropertyChanged?.Invoke(this, args);