C# Generic classes and casting with WCF

Question!

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.

  • I could write a specialized class for each MyGeneric<T> constellation, and there write an implicit type converter or implement a certain interface. But I want to avoid this.
  • I could have an interface with no generic, but the whole sense of the generic in this case is to get compile time type safety on the method Foo. So this is not an option.
  • Because Foo is a Operation Contract, it could not be generic itself.

Any ideas how this problem could be solved in C# 3.0?



Answers

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.

By : David B


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.



You want:

void Foo<T>(MyGeneric<T> b) where T : Base {}


This video can help you solving your question :)
By: admin