Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do C# objects know the type of the more specific class?

Tags:

c#

types

object

Suppose you create a generic Object variable and assign it to a specific instance. If you do GetType(), will it get type Object or the type of the original class?

like image 709
Kalid Avatar asked Nov 24 '08 23:11

Kalid


2 Answers

Yes.

You can also do:

object c = new FooBar();
if(c is FooBar)
     Console.WriteLine("FOOBAR!!!");
like image 114
Alan Avatar answered Sep 28 '22 07:09

Alan


Short answer: GetType() will return the Type of the specific object. I made a quick app to test this:

        Foo f = new Foo();
        Type t = f.GetType();

        Object o = (object)f;
        Type t2 = o.GetType();

        bool areSame = t.Equals(t2);

And yep, they are the same.

like image 23
Kalid Avatar answered Sep 28 '22 07:09

Kalid