Skip to content

Instantly share code, notes, and snippets.

@KvanTTT
Last active November 2, 2017 23:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KvanTTT/86b7b92514da9a409524 to your computer and use it in GitHub Desktop.
Save KvanTTT/86b7b92514da9a409524 to your computer and use it in GitHub Desktop.
using static System.Console;
using static System.Math;
using static System.DayOfWeek;
using static System.Linq.Enumerable;
namespace CSharp6Samples
{
public class Test
{
// Initializers for auto-properties
public string First { get; set; } = "Jane";
public string Last { get; set; } = "Doe";
// Getter-only auto-properties
public string First { get; } = "Jane";
public string Last { get; } = "Doe";
// Expression bodies on method-like members
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;
public void Print() => Console.WriteLine(First + " " + Last);
// Expression bodies on property-like function members
public string Name => First + " " + Last;
public Customer this[long id] => store.LookupCustomer(id);
static void Main()
{
// Using static
WriteLine(Sqrt(3*3 + 4*4));
WriteLine(Friday - Monday);
var range = Range(5, 17); // Ok: not extension
var even = range.Where(i => i % 2 == 0); // Ok
// Null-conditional operators
int? length = customers?.Length; // null if customers is null
Customer first = customers?[0]; // null if customers is null
int length = customers?.Length ?? 0; // 0 if customers is null
int? first = customers?[0].Orders?.Count();
PropertyChanged?.Invoke(this, args);
// String interpolation
var s = $"{p.Name,20} is {p.Age:D3} year{{s}} old";
var s = $"{p.Name} is {p.Age} year{(p.Age == 1 ? "" : "s")} old";
// nameof expressions
if (x == null) throw new ArgumentNullException(nameof(x));
WriteLine(nameof(person.Address.ZipCode)); // prints "ZipCode"
// Index initializers
var numbers = new Dictionary<int, string> {
[7] = "seven",
[9] = "nine",
[13] = "thirteen"
};
// Exception filters
try {}
catch (MyException e) when (myfilter(e))
{ }
// Await in catch and finally blocks
Resource res = null;
try
{
res = await Resource.OpenAsync(); // You could do this.
}
catch(ResourceException e)
{
await Resource.LogAsync(res, e); // Now you can do this …
}
finally
{
if (res != null)
await res.CloseAsync(); // … and this.
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment