1

Is possible to get the lower class of an inheritance at runtime without explicit cast?

Lets say we have three classes A, B and C.

class A {
    int _a;
}

class B : A {
    int _b;
}

class C : A {
    int _c;
}

And I have a generic method somewhere in the code.

void Foo<T> (T t) where T : A;

In the situation I have a list of references of the object A but I have to call Foo and pass to Foo the lower object type of the instance. In other method this list is fed with the A reference of some instances of B and other instances of C.

I want to be able to call Foo with the lower level of the instance without explicit casting. In my real situation I have tons of Bs and Cs inheriting from A and I there are a few methods which I have to do this job (I mean, this "implicit" downcast). I have to do something like this below.

In some place:

A tmp = new C();

In other place:

Foo<typeof(tmp).SomeMagicMethod()>(tmp);

The Type.SomeMagicMethod should be anything that I could use to implicit get the lower level of "tmp".

VMAtm
  • 27,943
  • 17
  • 79
  • 125
  • Your question doesn't make much sense to me, please reformulate it... – Willem Van Onsem Apr 07 '15 at 23:05
  • 3
    `Foo(tmp);` is not valid; generics is a compile-time feature. `T` must be a compile-time constant. – Blorgbeard Apr 07 '15 at 23:08
  • 1
    Hello @CommuSoft. I don't know how be more specific. Let me try to sum up my real problem. I have a application which implements a consumer/producer threading pattern. In the producer thread the list in my example are being fed with a high object of my inheritance tree to be able to store all the types of the inheritance. In my consumer thread I want to get these base-class references of the inheritance and implicit get the derivated class type in the inheritance tree of the reference I have in the list to be able to correct call a generic method which should receive the lowest derivated class – André Oliveira Apr 07 '15 at 23:12
  • Not at compile time, you could use reflection, etc. But that's all quite inefficient and is asking for trouble... – Willem Van Onsem Apr 07 '15 at 23:14
  • I see @Blorgbeard. So... Could you please read my comment above and try to shed some light on the problem? Thank you very much. – André Oliveira Apr 07 '15 at 23:15

1 Answers1

1

Quick answer is NO, you can't provide a non-explicit type for a generics in C#. This is done by design, as you have to provide full information about the type of variable you provide in method.

From other hand, you can remove the generic part of the method, and call it without type parameter. As you've already provide the type for the tmp, compiler will use that information for a generic type selection:

Foo(tmp);

See also Great Eric Lippert's answer for related question.

Community
  • 1
  • 1
VMAtm
  • 27,943
  • 17
  • 79
  • 125