Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Custom casting to a value type

Tags:

c#

.net

casting

Is it possible to cast a custom class to a value type?

Here's an example:

var x = new Foo();
var y = (int) x; //Does not compile 

Is it possible to make the above happen? Do I need to overload something in Foo ?

like image 968
Andreas Grech Avatar asked Jul 02 '09 09:07

Andreas Grech


2 Answers

You will have to overload the cast operator.

    public class Foo
    {
        public Foo( double d )
        {
            this.X = d;
        }

        public double X
        {
            get;
            private set;
        }


        public static implicit operator Foo( double d )
        {
            return new Foo (d);
        }

        public static explicit operator double( Foo f )
        {
            return f.X;
        }

    }
like image 80
Frederik Gheysels Avatar answered Sep 20 '22 13:09

Frederik Gheysels


Create an explicit or implicit conversion:

public class Foo
{
    public static explicit operator int(Foo instance)
    {
        return 0;
    }

    public static implicit operator double(Foo instance)
    {
        return 0;
    }
}

The difference is, with explicit conversions you will have to do the type cast yourself:

int i = (int) new Foo();

and with implicit conversions, you can just "assign" things:

double d = new Foo();

MSDN has this to say:

"By eliminating unnecessary casts, implicit conversions can improve source code readability. However, because implicit conversions do not require programmers to explicitly cast from one type to the other, care must be taken to prevent unexpected results. In general, implicit conversion operators should never throw exceptions and never lose information so that they can be used safely without the programmer's awareness. If a conversion operator cannot meet those criteria, it should be marked explicit." (Emphasis mine)

like image 27
Rytmis Avatar answered Sep 21 '22 13:09

Rytmis