Stefan Steinegger
Stefan Steinegger

Reputation: 64648

C# Generic classes and casting with WCF

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.

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

Upvotes: 1

Views: 1485

Answers (3)

Amy B
Amy B

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

Stefan Steinegger
Stefan Steinegger

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

Marc Gravell
Marc Gravell

Reputation: 1064044

You want:

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

Upvotes: 1

Related Questions