huseyin tugrul buyukisik huseyin tugrul buyukisik -4 years ago 120
C# Question

Why can't GetType().BaseClass find the base class?

In the below code,

Foo
is a base class of
Bar
right?

Then why compiler underlines the
.BaseType
part and says "the given expression is never of the provided (Form1.Foo) type"?

// has 1 virtual method
class Foo<T> : IList<T>
{
...
}

// overrides 1 method from Foo
class Bar : Foo<float>
{

}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
object o = new Bar();


if (o is Bar)
{
Console.WriteLine("2222222 "+ o.GetType().BaseType);
if(o.GetType().BaseType is Foo)
{
Console.WriteLine("2.5 2.5 2.5 2.5 2.5");
}
}
if (o is object)
Console.WriteLine("3333333");
}


output is:

2222222 VRAM.Form1+Foo`1[System.Single]
3333333


I'm trying to check if an
object
is assigned to an instance derived from
Foo
or not. Because in runtime, that object will be a primitive array or a
Foo<float>
or a
Foo<int>
or other
T
primitive types.

Also using
typeof(Foo<>)
for comparison doesn't work. I need only 1-depth checkĊŸ of wheter object o is derived from
Foo<>
or not. (I don't want to check all kinds like
Bar
Biz
Baz
that are integer double char types and many will be added later so I needed to check in 1line or 2 at most)

Answer Source

o.GetType().BaseType returns Type, not an instance you can check with is or as.

A better notation would be:

if(o.GetType().BaseType.GetGenericTypeDefinition() == typeof(Foo<>))

If you want to check equality of the type. Generally though it is better to use Type.IsAssignableFrom.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download