I have run into an odd casting issue while using generics. The following code will throw an InvalidCastException even though clearly an int can be cast to a double. Can anyone explain this behaviour and how to bypass it?
public class TestClass<T>
{
public T Cast(object o)
{
return (T)o;
}
}
public void Main()
{
TestClass<double> w = new TestClass<double>();
double x = w.Cast(10);
}
Edit:
Since I am in .net 4.0 land anyway I have changed it to use ‘dynamic’ instead of ‘object’ and everything works as expected. Appreciate all the spot-on and quick replies.
But an
objectcan’t be cast to adouble. Theoparameter takes anobject, not anint.For example, the following code fails with an
InvalidCastException: