Category Archives: .Net

Initialize a Dictionary with index initializers

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

A small but still significant feature in C# 6 is index initializers. Index initializers can be sued to initialize object members, but also dictionaries. Initializing a dictionary has always be cumbersome, but not anymore.

var numbers = new Dictionary<int, string>
{
  [7] = "seven",
  [9] = "nine",
  [13] = "thirteen"
};

There are other great new features in C# that I have not touched – have a look at the blog post New features in C# 6 by Mads Torgersen, Principal Program Manager, VS Managed Languages.

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.