Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast a generic Type to fit another generic method

Tags:

c#

generics

I have a method in Class A

public IList<T> MyMethod<T>() where T:AObject

I want to invoke this method in another generic class B. This T is without any constraints.

public mehtodInClassB(){
    if (typeof(AObject)==typeof(T))
    {
      //Compile error here, how can I cast the T to a AObject Type
      //Get the MyMethod data
        A a = new A();
        a.MyMethod<T>();
    }
}

Class C is inherited from Class AObject.

B<C> b = new B<C>();
b.mehtodInClassB() 

any thoughts?

After urs reminding...Update:

Yes. What I actually want to do is

typeof(AObject).IsAssignableFrom(typeof(T))

not

typeof(AObject)==typeof(T))
like image 652
ValidfroM Avatar asked Aug 24 '12 17:08

ValidfroM


People also ask

Why do we need cast in Java generics?

In collections there were lots of cast done. In a way, one of the main objective of Java generics is to help programmer reduce explicit type cast and provide type-safety. Before diving into detail it is better for you to go through the fundamentals of cast in Java. This is tutorial is a part of multi-part series on Java generics.

Is there a generic conversion operator in C++?

You cannot define a generic conversion operator, so you need it to be an explicit function. Moreover, a simple cast (U)t won't work, so you need Convert.ChangeType (which will work if your types are numeric). ( works as expected ). Note that Convert.ChangeType works only for types that implement IConvertible.

Is it possible to declare a double-cast for a generic type?

Oh yeah you're right. I use the double-cast in a bunch of generic designs, but it's always been for reference types. You cannot declare operators with additional generic type arguments, but you can declare ones to or from specific generic types like Point<int>.

Why do we need generic types?

Generic types have been around since .NET 2.0 and they can be extremely useful in creating flexible class designs that are extensible and can deal with different member types/elements. Most of the time they provide great enhancements, but dealing with casting in generics can become very complex especially if there are interdependencies in object.


1 Answers

If you know that T is an AObject, why not just provide AObject as the type parameter to MyMethod:

if (typeof(AObject).IsAssignableFrom(typeof(T)))
{
  //Compile error here, how can I cast the T to a AObject Type
  //Get the MyMethod data
    d.MyMethod<AObject>();
}

If providing AObject as a type parameter is not an option, you'll have to put the same constraint on T in the calling method:

void Caller<T>() where T: AObject
{
    // ...

    d.MyMethod<T>();

    // ...
}
like image 178
Dan Avatar answered Sep 28 '22 11:09

Dan