Pedro77
Pedro77

Reputation: 5294

How to cast to an unknown Type, need to cast to a GenericType, but T is unknown

I need to call the method DeepClone() from an object that I don't know the type.

object x = GetObject();
var x2 = x as IDeepCloneable< ?????? >;//What can I do here???
var clone = x2.DeepClone();

public interface IDeepCloneable<T>
{
    T DeepClone();
}

I have tried to create a new "base" interface and add ": IDeepCloneable" to the generic class.

public interface IDeepCloneable
{
   object DeepClone();
}

but in this case I need to change the method of the derived interface from T DeepClone(); to new T DeepClone();. As a result, all the classes that already implement IDeepCloneable< T> will not compile..

Upvotes: 2

Views: 201

Answers (2)

SLaks
SLaks

Reputation: 888107

You want a covariant interface:

public interface IDeepCloneable<out T>
{
    T DeepClone();
}

You can then cast to IDeepCloneable<object>.

Upvotes: 4

Mgetz
Mgetz

Reputation: 5138

In C# 4.0 the dynamic keyword allows you to work around this by suspending type checking until runtime:

dynamic x = GetObject();
var clone = x.DeepClone();

Will work fine insofar as there is a method DeepClone() on x

Upvotes: 2

Related Questions