C# 6.0
a nawet 7.0

Cezary Walenciuk

String interpolation

String interpolation



public class Person
{
    public int Height { get; set; }
    public int Weight { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public override string ToString()
    {
        string r = string.Format("{0} lat {1}  {2} cm"
            , Age, Name, Height);
        return "\{Age} lat \{Name}  \{Height} cm";
    }
}

String interpolation



public static void Fun()
{
    string hour = "\{DateTime.Now : hh}";
}
                

Expression-bodied members

Expression-bodied members



public class Person
{
    public int Height { get; set; }
    public int Weight { get; set; }

    public int BMI => Height / Weight;
}
    

Expression-bodied members



public class Point3D
{
    public int X => 15;
    public int Y => 22;
    public int Z => 33;
    public double Distance => Math.Sqrt(X*X + Y*Y + Z*Z);
}
 

Expression-bodied members



Dictionary initializer

Dictionary initializer



Dictionary<string, Person> _persons =
new Dictionary<string, Person>()
{
    { "programista", new Person() },
    { "grafik", new Person() }
}

Dictionary initializer


Dictionary<string, Person> _persons2 =
new Dictionary<string, Person>()
{
    ["programista"] = new Person(),
    ["grafik"] = new Person()
};

Dictionary initializer


Dictionary<string, Person> _persons =
    new Dictionary<string, Person>();

_persons.Add("programista", new Person());
_persons.Add("grafik", new Person());

Dictionary initializer


Dictionary<string, Person> _persons =
    new Dictionary<string, Person>();

_persons["programista"] = new Person());
_persons["grafik"] =  new Person());

Dictionary initializer


public Newtonsoft.Json.Linq.JObject ToJson()
{
    var result = new Newtonsoft.Json.Linq.JObject();
    result["height"] = Height;
    result["weight"] = Weight;
    result["age"] = Age;
    result["name"] = Name;
    return result;
}
public Newtonsoft.Json.Linq.JObject ToJson2()
{
    var result = new Newtonsoft.Json.Linq.JObject()
    {
        ["height"] = Height,
        ["weight"] = Weight,
        ["age"] = Age,
        ["name"] = Name
    };
           
    return result;
}

Using static members

Using static members


using System;
namespace CSharp6Example
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World");
        }
    }
}
}

Using static members


using System.Console;
namespace CSharp6Example
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteLine("Hello World");
        }
    }
}

Tylko klasy statyczne




Source: Cezary Walenciuk

Using static members


public static class StringExtension
{
    public static string JoinAndAddSeperator(string seperator,params object[] args)
    {
        StringBuilder sb = new StringBuilder();

        foreach (var item in args)
        {
            sb.Append(item + seperator);
        }

        return sb.ToString();
    }
}

Using static members


using System.Text;
using CSharp6Example.StringExtension;
using System.Console;

namespace CSharp6Example
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteLine(
                JoinAndAddSeperator(" : ",
                new object[] { 1, 22, 2, 33, 3, 44 }
                    ));
            ReadLine();
        }
    }
}

Using static members




Source: Cezary Walenciuk

Null propagation

Null propagation


public static class LoggerHelper
{
    public static string GetMethodName(System.Action action)
    {
        var name = "missing";

        if (action != null && action.Method != null)
        {
            name = action.Method.Name;
        }

        return name;
    }
}

Null propagation


using System.Text;
using CSharp6Example.LoggerHelper;
using System.Console;

namespace CSharp6Example
{
    class Program
    {
        static void Main(string[] args)
        {
            GetMethodName(SomeMethod);
        }

        public static void SomeMethod()
        { }
    }
}

Null propagation


public static class LoggerHelper
{
    public static string GetMethodName(System.Action action)
    {
        return action?.Method?.Name;
    }
}

Null propagation


public static class LoggerHelper
{
    public static string GetMethodName(System.Action action)
    {
       return action?.Method?.Name ?? "missing";
    }
}

Await in Catch/Finally

Await in Catch/Finally


public static class Operations
{
    public static async Task RunAction(Action action)
    {
        try {
            await SendStartedMessage();
            action();
            await SendOKMessage();
        }
        catch
        {
            await SendError();
        }
        finally
        {
            await SendDoneMessage();
        }
    }
    public static async Task SendError() { await Task.FromResult(0); }
    public static async Task SendOKMessage() { await Task.FromResult(1); }
    public static async Task SendStartedMessage() { await Task.FromResult(-1); }
    public static async Task SendDoneMessage() { await Task.FromResult(200); }
}

Exception Filters

Exception Filters


try
{
    action();
}
catch(Exception ex)
{
    if (ex.InnerException != null)
    {
        throw;
    }
}

Exception Filters


try
{
    action();
}
catch(Exception ex) if (ex.InnerException != null)
{
    throw;
}

Keyword : NameOf

Keyword : NameOf


public static void DoIt(string pesel)
{
    if (pesel == null)
    {
        throw new ArgumentNullException("pesel");
    }
}

Keyword : NameOf


public static void DoIt(string pesel)
{
    if (pesel == null)
    {
        throw new ArgumentNullException(nameof(pesel));
    }
}

Auto property Initializers

Auto property Initializers


public class Person
{
    private int _id;

    public int Id
    {
        get
        {
            return _id;
        }
    }
}

Auto property Initializers


public class Person
{
    private int _id = -1;

    public int Id
    {
        get
        {
            return _id;
        }
    } 
}

Auto property Initializers


public class Person
{
    public int Id
    {
       get; private set;
    } 
}

Auto property Initializers


public class Person
{
    public int Id
    {
       get; private set;
    }

    public Person()
    {
       Id = -1;
    }
}

Auto property Initializers


public class Person
{
    public int Id { get; } = -1;
}

C# 7.0 : Prmiary Constructors

C# 7.0 : Prmiary Constructors


public class Ruler
{
    public Ruler(string unitName, decimal value)
    {
        UnitsName = unitName;
        Value = value;
    }
    public string UnitsName { get; private set; }
    public decimal Value { get; private set; }
}

C# 7.0 :Prmiary Constructors


public class Ruler(string unitsName, decimal value)
{
    public string UnitsName { get; } = unitsName;
    public decimal Value { get; } = value;
}

C# 7.0 : Prmiary Constructors


public class Ruler(string unitsName, decimal value)
{
    public string UnitsName { get; } = 
        Guard.AgainstNull<string>("unitName",unitsName);

    public decimal Value { get; } = value;
}

public class Ruler(string unitsName, decimal value)
{
    public string UnitsName { get; } = unitsName ?? "cm";

    public decimal Value { get; } = value;
}

C# 7.0 : Declaration Expression

C# 7.0 : Declaration Expression


public static decimal ParseEase(string number)
{
    var amount = 0m;
    var boolean = decimal.TryParse(number,out amount);

    return amount;
}

public static decimal ParseEase(string number)
{
    if (decimal.TryParse(number, out var amount))
        return amount;
    return 0m;
}

C# 7.0 : Declaration Expression


public static double GetNumbersDividedBy3AndDoWeirdMath()
{
    int result = 0;

    var list = new List<int>() { 1212, 6454, 121584, 3435, 67, 43652, 343 };

    //var collection = list.Where(n => n % 3 == 1).ToList();

    foreach (var item in var collection = list.Where(n => n % 3 == 1).ToList())
    {
       result = result + (item /  collection.Count) ;
    }

    return result;
}

Dzięki