Skip to content

Instantly share code, notes, and snippets.

@tenor
Last active September 29, 2016 17:49
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 tenor/6f984b0fa2820a77cda17c15ec5a1264 to your computer and use it in GitHub Desktop.
Save tenor/6f984b0fa2820a77cda17c15ec5a1264 to your computer and use it in GitHub Desktop.
New features in C# 7
//See https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/ for more details.
abstract class Shape {}
abstract class Polygon : Shape
{
public virtual string NickName {get;}
public virtual int Sides {get;}
}
class Square : Polygon
{
public override string NickName => "Box";
public override int Sides => 4;
}
class Triangle : Polygon
{
public override string NickName => nameof(Triangle);
public override int Sides => 4;
}
class Circle : Shape {}
Shape shape = new Triangle();
//Switch statements with patterns
switch (shape)
{
case Polygon p:
Console.WriteLine($"{p.NickName} with {p.Sides} sides");
break;
default:
Console.WriteLine($"{nameof(shape)} is not a polygon!");
break;
case null:
throw new ArgumentNullException(nameof(shape)); //null case isn't matched by default case
}
//See https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/ for more details.
//Tuples with deconstruction
(string, int) GetKeyAndValue()
{
var sides = 3;
return (GetNameOfShape(sides), sides);
//Local function
string GetNameOfShape(int noOfSides)
{
return noOfSides == 3 ? "triangle" : noOfSides == 4 ? "quadrilateral" : "unknown";
}
}
var (key, val) = GetKeyAndValue();
Console.WriteLine(key);
//Out variables
if (Int32.TryParse("42", out int result)) //result variable is declared here
{
Console.WriteLine(result);
}
//Throw expressions
string Throws()
{
string s = null;
return s ?? throw new InvalidOperationException();
}
try
{
Throws();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment