Monday, February 21, 2011

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.

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

    Marc Gravell : Minor correction: it is actually a _conversion_ operator (see 10.10.3 in the MS spec)
  • 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; }
        }
    
    cbp : Oooh always new things to learn - can't believe I've never come across this before
    Marc Gravell : 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)
    John Rudy : 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!)
    Robert S. : Wow. That is awesome. I never knew about that. You rule.

0 comments:

Post a Comment