Search code examples
c#structtypeconverter

C# : How does this work : Unit myUnit = 5;


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; }
        }