C# - Why Overloads Instead of Optional Parameters? And AOP.

I just came across an old post on Dan Fernandez's blog that links to the "Whiteboard with Anders" session from TechEd 2004.  I was lucky enough to watch this event live.  One of the memorable questions answered - one that I often hear from ex-VBers - is why C# uses overloads instead of optional parameters ...

Watch the video because it has lots more, but here is the answer from the transcript:

Hejlsberg:

"Okay. The question is, Why don’t we have default parameters? I think there are a couple of reasons. First of all, they’re somewhat duplicative of overloading. I mean you can do the same with overloading, and which is indeed what people do today, but yes, you’re right. It’s more typing for sure. I think the other one is subtler, and in retrospect maybe not as important as I thought. Originally in the language design are- our issue with default parameters is that they burned the default into the call site as opposed to leave it up to the implementation. If you do overloads, let’s say you have void f, and then, let’s say, you have void f of index, for example, and void f of index is where the work happens, right? Then in this guy here, you simply say echo 5, because your default is 5. When the user calls f, it is up to you to change- you can change what your default is later in v2 of your API. When you have a call f somewhere, this by the compiler is translated into f of 5 in the call site, because it just copies that value. Now you can never change the default. This gives you more flexibility, but- and I thought that that was important. Perhaps it’s not all that important, but ... "

There was also an interesting informal discussion after the session where Michael Palermo (my co-volunteer in the development cabana that day) was discussing the AOP questions with Anders.  Anders was not aware of some AOP experimentation that had been done with C# using some Remoting mechanics (System.ContextBoundObject) - Michael couldn't remember the source at the time.  I remembered it being from an old MSDN article that a colleague had once shown me.  It is worth looking at the sample to see how it works - plus it was a good feeling to be one up on Anders! :-)

1 Comment

Comments have been disabled for this content.