Sunday, March 13, 2011

A thing I just discovered about typing in C#

Let's see if I can type a coherent post about what I think I just learned.

You have some hierarchy of classes:

class Foo {}
class Bar : Foo {}

Then you have some method that takes the base class but wants to know actual type of the object passed in:

class Baz
{
    static void DoStuff(Foo someObject)
    {
        Console.WriteLine(someObject.GetType());
    }
}

...

Baz.DoStuff(new Bar());


Will output:

Foo

I guess I've been out of the static language game for too long because I would've expected that to print out the name of the class passed in at runtime (in this case, Bar). Apparently it doesn't work that way. Probably has something to do with C# being a static language. I don't know, I'm not a compiler designer.

I got it to do what I wanted with generics:

static void DoStuff(T someObject) where T : Foo
{
    Console.WriteLine(someObject.GetType());
}

This will output Bar as expected. It also gives me a reason to use generics when previously I was scratching my head and wondering "Why wouldn't you just call GetType() on the object passed in?" Well THAT's why, STUPID. God.

No comments:

Post a Comment