Friday, January 19, 2007

Methods and dynamic casting in C#

I remember a month ago I was trying to do something similar with C++ and it doesn't work (suprise suprise :> ). I thought I'd see if it'd work in C# - and suprisingly it does. Ok, so what I am I babbling about?

Imagine you have an object Item and another object
StackableItem : Item
, that inherits from Item. Now imagine I have an array of Items. I can put Stackable items in here and I can put items in here, no problem. But when I come to use the array I don't know which are items and which are stackable items. To find out which are which I might use a dynamic cast, or in C# you can use method overloading and the program will do the dynamic cast for you (I assume it does that anyway).

public void AddItem(Item item)

{

    Console.WriteLine("Not so clever");

}

 

/// <summary>

/// Is C# clever enough to go to the correct one?

/// </summary>

/// <param name="item"></param>

public void AddItem(StackableItem item)

{

    Console.WriteLine("Very clever");

}



So in the above if I have:


Item i = new StackableItem();
inventory.AddItem(i);


The second function will be called. Neat right? Yes, yes it is.

3 comments:

Echo said...

Heh, I really should get around to adding an inventory system to my RPG. It's one of those simple things that I keep putting off.

I probably won't do anything nearly this neat though.

Ralf Westphal - One Man Think Tank said...

@Dan: How did you manage to get the C# source code into your blog posting? It´s so nicely formatted.

-Ralf

Dan said...

There's a plugin for visual studio that allows you to cut C# code as formatted html. (It's free)

But at the moment I can not remember the name. Also I remember it was somewhat unpleasant to get working with VS'05 as it was built for '03 but by now there's probably a new version?