C# 7: binary literals, digit separators, out variables

Within this article I want to introduce some of the minor but helpful new features. These are binary literals, digit separators and out variables.

Binary Literal

So far, we could use decimal and hexadecimal literals in C#. With C# 7.0 a third type is supported, the binary literal.

static void Main(string[] args)
{
  int x = 42;       // decimal literal
  int y = 0x2A;     // hexadecimal literal
  int z = 0b101010; // binary literal
}

Digit Separators

Decimal, hexadecimal and binary literals may be difficult to read if they are long. With C# 7.0 we could use the underscore character within such literals as digit separators. The use of digit separators will not change the meaning of the literal. But you can increase the readability of your literals if you use them wisely.

static void Main(string[] args)
{
  int x = 1_542;          // decimal literal
  int y = 0x2A_BF_71_4D;  // hexadecimal literal
  int z = 0b1011_1010;    // binary literal

  int max = Math.Max(1_513, 2_712);
}

Out Variables inline declaration

With C#7 output variables can be declared inline directly when passing to the method.

static void Main(string[] args)
{
  // C# 6 style
  int x;
  DoSomething(out x);
  Console.WriteLine(x);

  // C# 7 style
  DoSomething(out int y);
  Console.WriteLine(y);
}

private static void DoSomething(out int value)
{
  value = 5;
}

In my opinion this feature is a matter of taste. On the one hand you become the possibility to slim down the source code but on the other hand the variable declaration will be hidden inside the method call. In some situations, the source code readability may be increased by using the inline declaration but in other cases the explicit declaration outside of the method will increase the readability. For example, in cases were the variable is used in several places within a complex function it may be better to declare it explicitly at the beginning of the function instead of using the hidden inline declaration.

Werbung
Dieser Beitrag wurde unter C# veröffentlicht. Setze ein Lesezeichen auf den Permalink.

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit deinem WordPress.com-Konto. Abmelden /  Ändern )

Facebook-Foto

Du kommentierst mit deinem Facebook-Konto. Abmelden /  Ändern )

Verbinde mit %s