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 B
s and C
s 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".
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);