Reputation: 64648
I want to write a generic class that should be casted to itself with a different generic argument.
class Base {}
class Inherited : Base {}
class MyGeneric<T> {}
// WCF Service interface
void Foo(MyGeneric<Base> b);
// somewhere else
MyGeneric<Inherited> inherited;
Foo(inherited)
I know that this could be done in C# 4.0, but this doesn't help for now.
MyGeneric<T>
constellation, and there write an implicit type converter or implement a certain interface. But I want to avoid this.Any ideas how this problem could be solved in C# 3.0?
Upvotes: 1
Views: 1485
Reputation: 110211
the whole sense of the generic in this case is to get compile time type safety on the method Foo
The purpose of casting in this way (to a type that is not in the instance's ancestry), is to break type safety. Don't break type safety to save type safety.
Upvotes: 0
Reputation: 64648
I wrote this casting method
public MyGeneric<TTarget> Cast<TTarget, TSource>()
where TTarget : class
where TSource : TTarget, T
{
return new MyGeneric<TTarget>();
}
which could be called like this
MyGeneric<Inherited> inherited;
Foo(inherited.Cast<Base, Inherited>());
The ugly thing is that one has to provide the class that it already is. There is probably some improvement possible.
By the way, I couldn't manage to make it an extension method, to avoid the second generic argument.
Upvotes: 0