views:

819

answers:

2

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.

+2  A: 

You need to provide a cast operator for the class that takes an Int32.

Phil Wright
Minor correction: it is actually a _conversion_ operator (see 10.10.3 in the MS spec)
Marc Gravell
+27  A: 

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; }
    }
Marc Gravell
Oooh always new things to learn - can't believe I've never come across this before
cbp
There is also an "explicit" cast - works the same, but the caller must add (Unit); generally used when there is a risk of data loss (precision/range/scale/etc - for example float=>int)
Marc Gravell
Overloading operators is very powerful, but tread lightly when you do so: It's easy to make code that winds up being very unpredictable for the maintenance programmers. Use it when it's appropriate (such as the Unit case), but don't overdo it. (And always make sure it's well-documented!)
John Rudy
Wow. That is awesome. I never knew about that. You rule.
Robert S.