Dynamic cast with generics

  • Thread starter Thread starter Néstor Sánchez
  • Start date Start date
N

Néstor Sánchez

Hi,
i'm trying to solve the next problem ...

public class BaseType {...}
public class DerivedType : BaseType { ... }

public abstract class BaseClass
{
public abstract Type getGenericType();
}

public class DerivedClass<TheType> : BaseClass where TheType : BaseType
{
public override Type GetGenericType()
{
return typeof(TheType);
}
}
.. . .
public class Example
{
public static void Main()
{
. . .
DerivedClass<DerivedType> TransferedObject = new
DerivedClass<DerivedType>();
TheCall(TransferedObject);
}
public void TheCall(BaseClass AnObject)
{
Type GenericType = AnObject.GetGenericType();

// PROBLEM... this is what i tried to .. .
TheProcess(AnObject); // Cannot because C# doesn't suppor variance
for generic types
TheProcess((TheClass<GenericType>) AnObject); // Cannot because
GenericType is a variable, not a type
}

public void TheProcess(DerivedClass<BaseType> Value)
{
. . .
}
}

----------------
So... I need to cast a reference from an ancestor type to a derived type
dynamically.
Maybe Reflection has the solution?
Any help will be appreciated.


Néstor.
 
If you are using generics, then *use* generics. For instance:

public void TheCall<T>(T AnObject) where T : BaseClass {...}
public void TheProcess<T>(DerivedClass<T> Value) where T : BaseClass
{...}

As you say, another option is reflection - but this should be a last
ditch solution. Is there a (good) reason why you can't use the above?
As the answer to this may influence the best answer...

Marc
 
....the problem is that I don't know that is the derived type used.
The scenario is the following...
I have a namespace with types and classes that defines a business model.
Then, in another namespace, I have the presentation layer where I only need
to know the base types just to show values thru polymorphism (i.e:
AnObject.ToString()).
In other words, at the caller level there is irrelevant any detailed
(derived) information, but still there is need to reference the objects...
how?.
Thanks,

Néstor.
 
Then yes, reflection may be your best bet. In this scenario I would
use GetType() and MakeGenericMethod to invoke the method (as above) so
that my reflection is limited to the invoke step, rather than
throughout.

Watch for wrap: <http://msdn2.microsoft.com/en-us/library/
system.reflection.methodinfo.makegenericmethod(VS.80).aspx>

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top