I have a class declared as such:
public abstract class CrmAttribute <T> : ICrmAttribute
{
}
And in one of the methods further down I have this
castedValue = (T)value;
castedValue is then used in other methods of type T as a parameter.
My problem is a case has come up such that the above cast throws an InvalidCastException.
From what I can tell this is one specific case; In Dynamics 2011 Microsoft finally moved away from custom types like CRMNumber and moved to inherent .Net types but not for all cases. Of the ones that remain, is a complex Money type that has one property of .Value which contains a decimal. This is where my Exception is thrown as I cannot cast a decimal to a Money type. Even though a Money object is essentially a Decimal.
I’m still fairly new to generics and much of this is inherited code so I’m well aware the correct response is to not do this per se, But all I want to do is to be able to create my own implicit cast of type Money to Decimal so that the line using T will cast correctly.
Is this possible?
Your best bet is to add code to your class around the cast to test if T is the problematic type and perform the appropriate conversion instead of relying on cast.
Perhaps something like this: