Method Overloading in C#

November 2, 2010 5:06 am

In the words of a 90's action movie: "Alright, pop quiz".

What would the output of the following program be:

  1. class Program
  2. {
  3.     public static void Main(string[] args)
  4.     {
  5.         int x = 0;
  6.         int y = 1;
  7.         Test(x);
  8.         Test(y);
  9.         Test(1);
  10.         Test(0);
  11.     }
  12.     public static void Test(object obj)
  13.     {
  14.         Console.WriteLine("Object Overload");
  15.     }
  16.     public static void Test(System.DayOfWeek day)
  17.     {
  18.         Console.WriteLine("Enum Overload");
  19.     }
  20. }

If you run this code under .NET 3.5 you will see the following:

Object Overload
Object Overload
Object Overload
Enum Overload

So we pass in the same type (Int32) but we end up calling different method overloads. It also seems that the specific values that we are using matters. That seems a bit counter intuitive.

What is going on? What is happening is that the C# compiler is resolving the Test(0) call to the enum overload method. The reason can be found in the C# Language Specification 4.0:

the literal 0 implicitly converts to any enum type

So the literal 0 will resolve to the enum overload method due to the implicit conversion. That is why the call with a variable set to 0 resolves to the expected object overload.

This can cause some confusion when using a class that has an enum and object overload. A common scenario is when using SqlParameter. If you specify a literal 0 to the SqlParameter constructor then it will use the overload SqlParameter(String, SqlDbType) which will set the type of the parameter and not the value and is probably not what is wanted. To get around this simply cast or convert to any object type. Since we are using an int then converting to Int32 will make our intent clear:

  1. Parameter p = new SqlParameter("@pname",
  2.     Convert.ToInt32(0));

An alternative would be to use a variable instead of a literal:

  1. private static readonly int zero = 0;
  2. ...
  3. Parameter p = new SqlParameter("@pname", zero);

Honda Transmission Failure

September 14, 2010 5:57 am

The automatic transmission on my 2003 Honda Accord LX V6 packed it in.  I was surprised since Honda has a good name for quality and I own a 1997 Acura 1.6EL that is a great little car.

Another one bites the dust! I have a 2003 Accord LX V6 with 109,000 miles. Running cold was OK, but once warm, the revs shot up without shifting and then abruptly downshifted which dramatically slowed the car down. Twice when stopped at a light the car came totally out of gear. Since the problem was intermittent the dealer charged me $50 and said they don’t see an issue but to monitor the situation. Of course, on the way home, the problem occurred again. Went back to the dealer and they now seemed very interested in making the problem go away. The service adviser brought in the service manager who denied any defects with the transmission and that the 2004 recall couldn’t have anything to do with the fact I needed a new transmission. The dealer quoted me $6300 for a new Honda transmission and also got me quotes for a used and a rebuild ($4200 and $3200 respectively). When I said that the price for a new transmission with tax was ridiculous and that for that price I should just cut my losses they were very quick to get the used car manager to call around (he wouldn’t take the car since the tranny was broken) to get quotes (the highest was $2700). As I said, they seemed very eager to go out of their way to make the problem go away without costing them anything and they wouldn’t go to bat with Honda for me because of the service records (don’t get me started on that one!). I didn’t press the issue and found an independent transmission shop to do a rebuild for $1800. The owner there said that they see a lot of transmissions from V6 Honda’s (Accord, Odyssey, and Acura TL).

After doing some internet research it does seem like there are some major problems with this car.  I found a good page here.  A very interesting discussion of what the problem is can be found here.  I was also surprised to see that the car was the fourth worst vehicle third worst vehicle at  The majority of the issues reported there were transmission related.  Also, the NHTSA has 440 complaints (as of Nov 1, 2010) regarding this car's transmission.

I’m very disappointed in my car because I thought it would be more reliable but I'm really disappointed with the way Honda is ignoring this issue;  I won’t be buying any of their cars anytime soon.

Great Pool Site

5:26 am

Last year I had a problem with my pool water.  After searching the internet I was convinced I had a pink algae problem along with white water mold.   The only problem was that I didn't really know how to address the issue.  This was compounded by the fact that my pool is one of those temporary pools (15' round x 3') and I didn't feel like most of the generic answers addressed my situation.

Luckily I stumbled on the web site  It's a fabulous resource but the best part is that you can actually ask Alan a question and he will get back to you (sometimes within a few hours) with great practical advice and information.

In case you were wondering, I switched my pool from chlorine to bromine and solved all of the pool water issues within a day or two.  Thanks Alan!

The Fog Of War

November 24, 2009 5:51 am

I don't know if The Fog of War is the best documentary ever made but it is definitely one of the most intriguing.

The Fog of War

It works on so many levels. As an historical document of the cold war it is a fascinating look behind the curtain. As a philosophical discussion  it poses many difficult ethical questions.  And as a portrait of a conflicted individual it is an engrossing look at Robert McNamara.

Overall, The Fog of War is a highly recommended documentary that leaves you feeling a little smarter for having seen it.

Exception Shielding

July 7, 2009 4:34 am

My previous post spent over 600 words knocking down the Exception Handling Block, but version 3 and higher does have one nice feature: WCF Exception Shielding.  This allows exceptions received by a WCF service to be mapped to Fault Contracts.

Exception shielding is important in order to hide internal implementation details from service consumers.  This can make your service easier to use and, more importantly, prevent exposing sensitive internal information in your exceptions.

Enterprise Library Exception Shielding seems to be a good use of configuration to decouple a service interface from the underlying implementation.

Exception Handling (Block) & Enterprise Library

May 17, 2009 4:38 am

Lately, I've been thinking about exceptions vs. error codes. As usual, Joel On Software has a couple of well thought out posts on the topic. The first post makes the point that exceptions "create too many possible exit points for a function". The second post, Making Wrong Code Look Wrong makes some very good points on exception handling as well as other topics. In the same way that compile time errors are better than runtime errors, it is better to find errors in code simply by reading the code than by being forced to run or debug the code. That seems like a pretty straight forward statement to me but I'm wondering if people actually agree with it -- what with the popularity of various frameworks where everything is hung together with configuration files.

Those two ideas -- exceptions as flow control and making code look wrong -- led me to think about why I really, really dislike Microsoft's Enterprise Library Exception Handling Block: it combines the worst parts of both.

Consider the following:

  1. try
  2. {
  3.     DoSomething();
  4. }
  5. catch (Exception e)
  6. {
  7.     bool rethrow =
  8.         ExceptionManager.HandleException(e,
  9.             "MySpecialPolicy");
  11.     if (rethrow)
  12.     {
  13.         throw;
  14.     }
  15. }

My objection: you have no idea what the exception handler does!

Since you can't tell what will happen at this one point, you can't mentally trace the program flow to see if it's logically sound. This makes development, tracking down bugs, and overall maintenance difficult.

"Wait, wait, wait", you say. "You can create meaningful policy names to avoid this kind of confusion". Yes, you can change the policy name to something more meaningful like "BusinessLayerMustRethrowPolicy" so you can understand the intent of the code -- which is a good thing. However, you still have no idea of the actual behavior at run time since the configuration could be set to not rethrow (for some reason). Plus, if you are making your exception handling configuration based, then you are implicitly saying that you allow the configuration to be changed to another setting (e.g. not rethrow an exception). Isn't that the point of putting things in configuration? To allow behavior to be changed without changing the code.

Since throwing an exception changes the flow of the program, if you modify the Exception Handling Block configuration (behavior) then you are actually creating a new execution path. Does that mean the program should run "properly" for all possible settings of the configuration? (Not likely!) Do you then have to test all of those possible code paths?

Maybe you could implement a policy of no configuration changes without a full test cycle but then how is that much different than performing a code change? You do skip the issue of introducing a new coding bug
and you avoid a build but you still need to create some sort of deployment package and go through a release cycle (which is the most expensive part in this lifecycle). Plus there is always the chance of the configuration becoming incorrect "by accident" and the new execution path may introduce some undesirable behavior. e.g. maybe database changes are committed because, even though an exception occurred, the policy said to not throw an exception and the calling code assumed that all errors would be reported as exceptions.

Other objections to the Exception Handling Block:

  • As a framework, the "if rethrow" construct doesn't really offer a lot of abstraction; you still need to pepper your code with "if rethrow" code in every catch block.
  • If you try to use the logging block to log an exception, every log entry for that handler shares all of the same basic log entry information (e.g. event ID). This can be restricting if you need that kind of control.

In general, I avoid the Exception Handling Application Block because it obfuscates the functioning of the program which makes the program harder to understand and maintain. To me this outweighs any functionality provided by the block.

Farewell, Scrubs

May 12, 2009 4:38 am

Scrubs wrapped up what looks to be its final season with a really good 1 hour finale.  The last 2 seasons have been hit and miss and rarely hit the incredible highs of previous years but it was nice to see Scrubs rescued by ABC so it could end its run on its own terms. The finale was a fitting end to one of the funniest and most under rated shows ever. Scrubs, more than any other show, could play broad comedy one minute and the next minute be deadly serious. You'd think the effect would be too jarring but somehow they made it work.

In honor of the finale here is my list of best Scrubs episodes (in no particular order -- almost):

1. My Old Lady

2. My Monster

3. My Own American Girl -- Elliot gets a backbone!

4. My Occurrence

5. My Screw Up

And, in my opinion, the best Scrubs episode ever:
6. My Way Home

Foods I Miss #2

February 1, 2009 6:02 am

Sarasoda was "the sparkling citrus cooler for adults" (as the ad says) that had a minimal alcohol content.  It was mainly available in the 80's and I"m not sure if it was specific to Canada or if it was widely available. It was expensive for the time -- I seem to remember it selling for the very high price of 1 dollar.  Obviously, at that price this was a beverage only for special occasions.  :)

Although I was not quite an adult, I still bought quite a few over the years and they were worth the extra money.  Yum!


If anyone has any other information or memories please share.

Nice Try, QuickTax

January 29, 2009 5:49 am

I got my new copy of QuickTax in the mail the other day.

No, I didn't pay for it.  I didn't even ask for it!

In a previous post, I wrote about why I wouldn't be using QuickTax any longer. It seems that Intuit has decided to mail out physical CDs of QuickTax in the hope of getting folks to install it and then purchase the software.  I think it reeks of a desperate attempt to recapture their lost sales and I'm hoping that people don't fall for this and that this ends up costing Intuit more money than they recoup.

Yes, I'm still bitter over last years money grab.  :)

Foods I Miss #1

January 10, 2009 5:31 am

Number one in a series (?) of "foods that I wish I could still eat". Maybe I'm watching too much Food TV or something?

For the first installation, we honor the late great cereal: Crispy Wheats 'N Raisins.  For those of you who don't remember, Crispy Wheats 'N Raisins launched in the late 70's and, in 1996, was re-branded Crispy Wheaties 'N Raisins.  Unfortunately, even that name change couldn't change the cereal's fortune and it was eventually discontinued.

Man, that was a good cereal.

I couldn't track down the classic "Wizard of Oz" commercials so here is another one:

Anyone have any other selections?