Skip to content

Instantly share code, notes, and snippets.

@ashmind
Last active Aug 17, 2017
Embed
What would you like to do?

String interpolation

var x = 1;

// same as string.Format("A {0} B", x) 
var y1 = $"A {x} B"; // y == "A 1 B"

// $@ for multiline
var y2 = $@"A
{x}
B";

// Formatting
var y3 = $"A {1.23:F1} B"; // y == "A 1.2 B"

Operator ?.

// same as (person != null ? person.Name : null)
var name1 = person?.Name;

// same as (person != null ? person.Name : "(Unknown)")
var name2 = person?.Name ?? "(Unknown)"; 

Using static

using static System.Console;

public class Program {
    public static void Main(string[] args) {
        WriteLine("Test");
        ReadKey();
    }
}

Auto-property improvements

// initializers
public string FirstName { get; set; } = "Jane";

// getter-only auto-properties
public string FirstName { get; } = "Jane";

Expression bodies

// methods (same as Sum(int a, int b) { return a + b; })
public int Sum(int a, int b) => a + b;

// properties (same as Length { get { return End – Start; } })
public string Length => End - Start;

nameof()

public void M() {}
public void X() {
    // Good for refactoring, compiler-verified:
    Console.WriteLine(nameof(M)); // => M
} 

Index initializers

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

Exception filters

try {
    // ...
}
catch (WebException ex) when (ex.Status == WebExceptionStatus.Timeout) {
    // ...
}
@stevehansen
Copy link

stevehansen commented Oct 20, 2015

var name2 = person?.Name ?? "(Unknown)"; 

is actually the same as

var name2 = (person != null ? person.Name : null) ?? "(Unknown)"

because when person.Name is null it will also use "(Unknown)"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment