C#: Custom casting to a value type
.net, c#, casting
Solution
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;
}
}
Problem
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` ?