The blog of Tobin

Tobins nerd blog on .NET, Software, Tech and Nice Shiny Gadgets.

Tuesday, November 21, 2006

.NET 2.0 Got Better with Dynamic Dispatching

Ok, I'm behind the times. Despite using .NET 2.0 on a few small projects, I've not fully got into all the c# language improvements for .NET 2.0 yet.

However, today I was very pleasantly surprised to find that this works...

public void SayIt(String aString)
{
Console.WriteLine("I got a string {0}", aString);
}

public void SayIt(int anInt)
{
Console.WriteLine("I got a interesting int {0}", anInt);
}

public void SayIt(object anObject)
{
Console.WriteLine("I didn't get anything in particular, but it looks like this: {0}", anObject.ToString() );
}

SayIt("Hello"); // outputs "I got a string Hello"
SayIt(2); //outputs "I got an interesting int 2"
SayIt(new System.Net.Cookie("lastLoggedIn","01-Jan-2006"));// outputs "I didn't get anything in particular, but it looks like this: lastLoggedIn=01-Jan-2006"


This is cool stuff - it's called Dynamic Dispatching, and it makes solving certain problems much easier. For example, if you've ever tried to use the Visitor pattern in .NET, you'll know what I mean: dynamic dispatching lets you set up handlers for each node type in the heirarchy without using statements such as if(node is string){...}else if(node is Cookie){...}.

Similarly, I recall trying to set up some kind of multicast pattern in .NET, but being stumped (I learnt about this in the Pattern Hatching book). The new addition of Dynamic Dispatching should allow recievers to be set up quite easily, interesting stuff indeed!...

This is all good, I'm looking forward to checking out c# v2 a little more.

If anyone knows any good books/sites that hightlight all the new language features, then I'm all ears! For anyone who's interested, I found the dotnetcat.com site seemed to show a few cool new capabilities in concise format.

Labels: , ,

1 Comments:

Anonymous Anonymous said...

Um, no.
That is call overloading, not dynamic dispatch.

The cool thing would have happened if you could do this in runtime, which it isn't doing.
That is why we have the Visitor pattern

7:27 PM  

Post a Comment

<< Home