The TypeAlias<T>
has a Value
property which stores the value of the instance. It implements IEquatable<TypeAlias<T>>
in a way that uses its value to determine equality with other instances. Additionally IEquatable<T>
is implemented so it can be compared with values of type T
. This means that for example the equality between a TypeAlias<string>
and a string
can be determined. The corresponding operators ==
and !=
are also overloaded. Last but not least the implicit cast operator is implemented for T?
which makes it possible to for example cast a TypeAlias<int>
to an int
.
So how would I implement the AnimalType
enum from above as a TypeAlias
and perform similar operations as above? The implementation of the TypeAlias
is provided in the next snippet.
public class AnimalType : TypeAlias<string>
{
private AnimalType(string value)
: base(value) { }
public static AnimalType Dolphin { get; } =
new("Dolphin");
public static AnimalType Hippopotamus { get; } =
new("Hippopotamus");
public static AnimalType Tiger { get; } =
new("Tiger");
public static IImmutableSet<AnimalType> PossibleValues { get; } =
new HashSet<AnimalType>() { Dolphin, Hippopotamus, Tiger }
.ToImmutableHashSet();
public static AnimalType? FromString(string value)
{
StringToAnimalType.TryGetValue(value, out var animalType);
return animalType;
}
private static readonly IImmutableDictionary<string, AnimalType> StringToAnimalType =
PossibleValues.ToImmutableDictionary(e => e.Value, e => e);
}
Using the new AnimalType
as string can be achieved by calling the ToString()
method similar to the enum example above or by using the implicit conversion as demonstrated below.
string dolphin = AnimalType.Dolphin;
There is no need to validate if a value is defined or not when using a variable of type AnimalType
because it is not possible to produce an instance of the AnimalType
that contains an invalid value. To create an instance of AnimalType
from a string the FromString
method can be used that returns null
when the value is invalid.
Not only does using the TypeAlias
class enable the creation of safer code it also works nicely together with EntityFramework Core value conversions to convert between raw values and TypeAlias
implementations. This means that all application code can use the safe TypeAlias
and values of primitive types and validations of those values only have to be present at the edges of the application.