C# : How does this work : Unit myUnit = 5;
-
03-07-2019 - |
Question
I just noticed that you can do this in C#:
Unit myUnit = 5;
instead of having to do this:
Unit myUnit = new Unit(5);
Does anyone know how I can achieve this with my own structs? I had a look at the Unit struct with reflector and noticed the TypeConverter attribute was being used, but after I created a custom TypeConverter for my struct I still couldn't get the compiler to allow this convenient syntax.
Solution
You need to provide an implicit conversion operator from int to Unit, like so:
public struct Unit
{ // the conversion operator...
public static implicit operator Unit(int value)
{
return new Unit(value);
}
// the boring stuff...
private readonly int value;
public int Value { get { return value; } }
public Unit(int value) { this.value = value; }
}
OTHER TIPS
You need to provide a cast operator for the class that takes an Int32.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow