Skip to content

Alias any type C# 12.0type safetycode reduction

Use the alias directive to give names to types like tuples.

Prior to this feature the using directive could create an alias for any named type.

C# 12 enables the using directive to create aliases for un-named types like tuples, pointer types etc.

Code

C#
using GeoCoordinate = (double latitude, double longitude);

GeoCoordinate location = GetLocation();
PrintLocation(location);

void PrintLocation(GeoCoordinate loc)
  => Console.WriteLine($"Latitude: {loc.latitude}, Longitude: {loc.longitude}");

GeoCoordinate GetLocation() => new(1.1, 2.2);
C#
// Remember (double latitude, double longitude) is a Geolocation

(double latitude, double longitude) location = GetLocation();
PrintLocation(location);

void PrintLocation((double latitude, double longitude) loc)
    => Console.WriteLine($"Latitude: {loc.latitude}, Longitude: {loc.longitude}");

(double, double) GetLocation() => new(1.1, 2.2);
C#
GeoCoordinate location = GetLocation();
PrintLocation(location);

void PrintLocation(GeoCoordinate loc)
    => Console.WriteLine($"Latitude: {loc.latitude}, Longitude: {loc.longitude}");

GeoCoordinate GetLocation() => new(1.1, 2.2);

record GeoCoordinate
{
    public double latitude { get; init; }
    public double longitude { get; init; }

    public GeoCoordinate(double latitude, double longitude)
    {
      this.latitude = latitude;
      this.longitude = longitude;
    }
}

More information