I have the following code:
public interface IDrilldown
{
void AddCriteria<T>(T Criterion);
}
public class MyClass<W> : IDrilldown // where W : class
{
void IDrilldown.AddCriteria<T>(T Criterion)
{
W value = Criterion as W;
...
}
}
Unfortunately, the cast I have above will not work unless W has the constaint in the code. I would like to have this using value types. Is it at all possible?
I cannot make W and T the same type. My interface does not have a type associated with it globally, only the internal data types.
This is so that I can have a List all having different T’s
I was able to find a way to do it, it’s a little hacky but allows it to work:
The only drawback with this is,
Convert.ChangeTypewill use converters to change between internal objects, sostring value = (string)Convert.ChangeType(1, typeof(string))will work and return"1"instead of throwing an exception.To clarify on how this works, the documentation states:
so for this method to work with custom types you will need to implement the
IConvertibleinterface to convert from one custom type to any other type. In the code sample above, if bothTandWare the same type, theConvert.ChangeTypewill succeed, even if the custom object does not implementIConvertiable.