Let’s continue being inspired by functional languages, and in particular other languages – F#, Scala, Swift – that aim to mix functional and object-oriented concepts as smoothly as possible.
- MadsTorgersen (C# language PM)
let me show you them
Real language support, not just System.Tuple
public (double meanAge, int oldest) GetAgeStats(IEnumerable<Person> people)
{
var mean = people.Average(x => x.Age);
var max = people.Max(x => x.Age);
var result = (meanAge: mean, oldest: max);
return result;
}
(var mean, var oldest) = GetAgeStats(people);
Dog - regular reference we have today
Dog! - a reference which cannot be null
Dog? - a reference which might be null
public destructible struct ImageResource
{
...
~Cleanup() { ... }
}
public class Celsius(double Temperature);
public class Fahrenheit(double Temperature);
public class Cartesian(double X, double Y);
public class Polar(double r: Radius, double phi: Angle);
public class Fahrenheit(double Temperature)
{
public bool operator is(Celsius c) { ... }
}
var someTemp = new Fahrenheit(212.0);
if(someTemp is Celsius(100.0))
{
//someTemp is boiling
}
var v = foo as Video;
if (v != null) {
//code using v
}
becomes
if (foo is Video v) {
//code using v
}
//v doesn't exist
abstract class Shape;
class Square(double Width, double Height) : Shape;
class Circle(double Radius) : Shape;
public double GetArea(Shape shape) {
switch(shape) {
case Square(1.0, 1.0): return 1.0;
case Square s: return s.Width * s.Height;
case Circle c: return Math.PI * c.Radius * c.Radius;
}
}
public record class Cartesian(double X, double Y);
public static class Polar
{
public static bool operator is(Cartesian c, out double R,
out double Theta)
{
R = Math.Sqrt(c.X*c.X + c.Y*c.Y);
Theta = Math.Atan2(c.Y, c.X);
return c.X != 0 || c.Y != 0;
}
}
var c = Cartesian(3, 4);
if (c is Polar(var R, *)) Console.WriteLine(R);
(sorry if you're colorblind)