An object value from a third party application provides a value that is correct but incorrectly typed. I’m trying to Type this object value in an generic method i’m creating into the type of my choosing. I’ve mocked up an example to demonstrate the problem.
static void Main(string[] args)
{
decimal d = 1; // this can't be changed
var v = Method<int>(d); // what I'm trying to do
}
//the code in this method can be changed
static T Method<T>(object input)
{
T output = default(T);
//causes InvalidCastException
output = (T)input;
return output;
}
As you can see the value ‘1’ is an valid integer, however as the third party application types it as a decimal, when trying to convert it to an integer it falls over. How can the generic method be changed so that it can won’t fall over for this scenario?
Replace
output = (T)input;with: