Referencia rápida

Chuleta de Características de C# 7.0

Guía de referencia rápida de C# 7.0: variables out, pattern matching, tuplas y desconstrucción, funciones locales, retornos por referencia y literales binarios.

· Publicado

Una referencia rápida de la sintaxis y características introducidas en C# 7.0 (.NET Framework 4.7 / .NET Core 2.0).

Variables out

Declare variables de salida directamente en la lista de parámetros al invocar un método:

// Antes de C# 7:
int result;
if (int.TryParse(input, out result)) { ... }

// En C# 7:
if (int.TryParse(input, out int result))
{
    Console.WriteLine($"Parsed number: {result}");
}

// Descartar parámetros out innecesarios con _
if (int.TryParse(input, out _))
{
    Console.WriteLine("Input is valid numeric");
}

Coincidencia de Patrones (Pattern Matching)

Patrones de tipo con is

public void PrintArea(object shape)
{
    if (shape is Circle c)
    {
        Console.WriteLine($"Circle area: {Math.PI * c.Radius * c.Radius}");
    }
    else if (shape is Rectangle r)
    {
        Console.WriteLine($"Rectangle area: {r.Width * r.Height}");
    }
}

Sentencias Switch con patrones y cláusulas when

switch (shape)
{
    case Circle c:
        Console.WriteLine($"Circle with radius {c.Radius}");
        break;
    case Rectangle r when r.Width == r.Height:
        Console.WriteLine($"Square {r.Width} x {r.Height}");
        break;
    case Rectangle r:
        Console.WriteLine($"Rectangle {r.Width} x {r.Height}");
        break;
    case null:
        throw new ArgumentNullException(nameof(shape));
    default:
        Console.WriteLine("Unknown shape");
        break;
}

Tuplas y Desconstrucción

Requiere el paquete System.ValueTuple en versiones anteriores:

Retornos con tuplas con nombre

(string First, string Last, int Age) GetUser()
{
    return ("Alice", "Smith", 30);
}

var user = GetUser();
Console.WriteLine($"{user.First} is {user.Age} years old");

Desconstrucción de tuplas

// Desconstruir en variables individuales
var (first, last, age) = GetUser();

// O en variables ya existentes
string f, l;
int a;
(f, l, a) = GetUser();

Funciones Locales

Declare métodos auxiliares anidados dentro del ámbito de la función que los contiene:

public int Factorial(int n)
{
    if (n < 0) throw new ArgumentException("Negative value", nameof(n));
    return Calculate(n);

    int Calculate(int x)
    {
        return x <= 1 ? 1 : x * Calculate(x - 1);
    }
}

Mejoras en Literales

// Separadores de dígitos (_)
int million = 1_000_000;
long hexMask = 0xFF_EC_00_12;

// Literales binarios (0b)
byte byteFlag = 0b1010_0110;

Locales y retornos ref

Devolver referencias a posiciones de memoria en lugar de valores copiados:

public ref int Find(int target, int[] numbers)
{
    for (int i = 0; i < numbers.Length; i++)
    {
        if (numbers[i] == target) return ref numbers[i];
    }
    throw new IndexOutOfRangeException();
}

int[] array = { 10, 20, 30 };
ref int val = ref Find(20, array);
val = 99; // array[1] becomes 99

Miembros con cuerpo de expresión

Sintaxis de cuerpo de expresión extendida a constructores, finalizadores y descriptores de acceso:

class Item
{
    private string _name;

    // Expression-bodied constructor
    public Item(string name) => _name = name ?? throw new ArgumentNullException(nameof(name));

    // Expression-bodied property accessor
    public string Name
    {
        get => _name;
        set => _name = value ?? "default";
    }
}

Temas relacionados