I must honestly say that I do not really understand much about casting, but I thought this would work.
I have a Generic Class Test:
public class Test<T,U>
{
T variable1;
U variable2;
//etc.
}
I need to use this class in a WPF view, and since you can’t create generic views in WPF (how lovely) I thought: lets just use a Test<object, object> for the view, since I am only concerned about working with the string representations of the variables in the view.
So I try:
Test<Foo, Bar> test = new Test<Foo, Bar>();
return test as Test<object, object>;
But that gives me:
Error 1 Cannot convert type 'DomainModel.Tests.Test<T,U>'
to 'DomainModel.Tests.Test<object,object>' via a reference conversion, boxing
conversion, unboxing conversion, wrapping conversion, or null type conversion
I would think that every object must be castable to object?
Anyhow, I am quite stuck now in how to ever use generic classes in WPF…
Any pointer in the right direction?
This is a generic variance issue. C# 3 does not allow variance in generic parameter types: thus,
IEnumerable<string>is not compatible withIEnumerable<object>. This restriction will be relaxed for safe scenarios in C# 4. But this won’t help for your case because C# 4 only supports variance on interfaces or delegates. And even if a future version of C# allows generic variance on classes, it still may not help you because it’s not clear thatTest<object, object>is a safe cast: suppose variable1 has a setter:You can however “cast” a
Test<string, string>toobject:WPF bindings will still then be able to access its properties via reflection.
Alternatively, define a non-generic interface that provides the functionality you need (in your case “the string representations of the variables”):
and implement this on your generic class. You can then access the stringised values via the interface members. (Obviously this particular interface example is stupidly bound to the implementation and in reality you would give it a name and members that reflected the business meaning of the data it exposes.)