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;
}
}Notes
- Works with tuples, pointer types, array types, and other types that previously could not be aliased
- The alias is scoped to the file, just like a regular
usingdirective - Combine with global using directives C# 10.0 to share aliases across your project