C#, how to create your own variable type
Do you know that you can create your own variable types in C# programming language.
Here is a good example.
In this code, only 1 or 0 can be assigned to the variable.
(Source: My Gist)
struct BoolInt
{
private readonly int value;
private BoolInt(int value)
{
this.value = value;
}
private int Value
{
get { return value; }
}
public static implicit operator BoolInt(int value)
{
if (value > 1 || value < 0)
{
throw new Exception("Value can be only 1 or 0");
}
else
{
return new BoolInt(value);
}
}
public static implicit operator int(BoolInt i)
{
return i.Value;
}
}
Usage:
BoolInt val = 0;
BoolInt val2 = new BoolInt();
val2 = 1;