Aug
14
2015

C# 6 Features in Action!

With Visual Studio 2015 available for all, I wanted to explore new language features in C# 6 that you can try right from this blog post!

Interactive Code Sample

// allows calling static members without class name
using static System.Console;
using static System.String;
using static System.Linq.Enumerable;

public class Person
{
    // auto property initializer
    public string FirstName { get; set; } = "John";
    public string LastName { get; set; } = "Doe";

    // readonly property initialized with expression body
    // assigned to value returned from string interpolation 
    public string FullName => $"{FirstName} {LastName}";

    // method defined with expression body
    public string GetLastNameFirst() => $"{LastName.ToUpper()}, {FirstName}";

    public void Test(string testName)
    {
        var dash = "-";
        var dashLength = 30 - testName.Length;
        // use {{ and }} for literal "{" and "}"
        // use {{{ and }}} to wrap a value within "{" and "}" 
        // repeating a dash with length not to exceed 30
        // WriteLine | Concat | Repeat == using static :) 
        WriteLine($"{{{testName}}} {Concat(Repeat(dash,dashLength))}");
        WriteLine(FullName);
        WriteLine(GetLastNameFirst());
        WriteLine();
    }

}
    
// test default
var um = new Person();
// nameof returns the string name of the instance
um.Test(nameof(um));

// test initialized
var palermo4 = new Person() 
   { FirstName = "Michael", LastName = "Palermo" };
palermo4.Test(nameof(palermo4));

// interactive!  click go -->
    Copyright © Microsoft Corporation. All rights reserved.
    The code provided in this post is licensed under the Microsoft Public License (Ms-PL).
blog comments powered by Disqus

Resources

Archives