My Leading Candidate for Worst C# Feature – Method Hiding

I love C#, I really do. Of course is has its little annoying quirks here and there, but in general it is, IMHO, one of the best static programming languages out there. Having said that, one thing that makes me wonder “WHAT THE HELL WERE THEY THINKNING?!?$?!?” every single time is the feature known as “Method Hiding”.

What is Method Hiding?

Method hiding, in short, is the crippled, mentally-ill brother of method overriding. For example, look at the next code:

class A
{
  public string GetName()
  {
    return "A"; 
  }
}

class B : A
{
  public new string GetName()
  {
    return "B";
  }
}

Class A has a GetName method; class B inherits from class A and implements the GetName method as well. 
Look carefully at the GetName method signature in class B – do you see the new keyword there? this means that the method doesn’t override the implementation in class A, it just hides it. What does that mean? read on.

So What’s the Big Deal? Hide, Override… Who Cares?

There is a huge difference in the behavior of method hiding and overriding. Look at the next two samples:

Method hiding vs. Method overriding

The left part is a method hiding example, and the right part is a method overriding example. Now let’s go through the use cases.

First – using the father classes:

FatherHidden fh = new FatherHidden();
fh.GetName(); // = "A"

FatherVirtual fv = new FatherVirtual();
fv.GetName(); // = "A"

Both are available and return the same result. Good.

Second – using the son classes:

SonHiding sh = new SonHiding();
sh.GetName(); // = "B"

SonOverriding so = new SonOverriding();
so.GetName(); // = "B"

Again, both methods return the expected result. Swell!

Third – using polymorphism – storing an instance of the son classes in a father class variable and calling the GetName method:

FatherHidden fh = new SonHiding();
fh.GetName(); // = "A"

FatherVirtual fv = new SonOverriding();
fv.GetName(); // = "B"

See that? the hidden method (FatherHidden.GetName) had suddenly woken up, took over and returned “A” instead of the expected “B”! kicking polymorphism out the door while doing it!

Is It a Problem?

Yes, it is. I’ve never found any reason to use method hiding and I can’t think of a good reason start using it in the future. OOP is great and I can’t understand why we need ways to screw it up. In my opinion, if you get to a situation where you need to use method hiding, re-think your design and start over.

This is not just a cute code smell. It can lead to nasty bugs along the way. For instance, I came across something like the next piece of code when doing a code-review lately:

class Base
{
  public bool IsAuthenticated { get { return false; } }
}
class SomeAuthClass : Base
{
  public new bool IsAuthenticated { get { return CheckAuthentication(); } }
}

Now, as long as they use SomeAuthClass variable types on their system, everything will work fine. But once a developer comes and wants to use some OOP magic, all users will immediately become unauthenticated. And this is no fun. No fun at all.

One of my major problems with method hiding is that it is C#’s default behavior – you don’t even need to write the new keyword. And even if the method on the base class is marked as virtual, and you forget to mark the method on the inheriting class with override – you fall back to method hiding…

#sadpanda

What I Am Suggesting

I know this feature isn’t going to disappear. Ever. I’m sure some people have found a reason to use it like there’s no tomorrow and Microsoft is one of the best in keeping their products backwards-compatible.

However, I would like:

  • To get a compilation error if a method is going to hide another method and is not marked with the new keyword.
  • To make the method hiding feature obsolete (yes, obsolete!) and get a compilation warning when using this feature in future versions of the framework.
  • You to stop using method hiding.
  • Everyone to recycle more and save the planet!

All the best,
Shay.

kick it on DotNetKicks.com Shout it




Windows Azure Tip: The "DeleteCurrentDeployment" task failed unexpectedly

Recently I’ve been helping a client to migrate an existing web application to the Azure cloud. We’ve been facing several different obstacles along the way, but most of them were technical. However, today we got to our first “DUDE, I HAVE NO IDEA WHAT’S GOING ON” moment – we got the next error when trying to build the Azure project in Visual Studio:

“Error 1  The "DeleteCurrentDeployment" task failed unexpectedly.
System.InvalidCastException: Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.VisualStudio.OLE.Interop.IServiceProvider'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{6D5140C1-7436-11CE-8034-00AA006009FA}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).”

*crying inside*

Searching the web resulted in a very few unrelated cases with crazy solutions - I even tried to run regsvr32 on all of the DLLs in the system32 folder… which didn’t help. At all.

*crying out*

Anyways! 2 hours later I had everything working again! How? read on…

The Solution

There is actually nothing fancy about the solution… The thing that worked for me was uninstalling Windows Azure SDK and Windows Azure Tools for Visual Studio and then reinstalling them. That’s it.

*tears of joy*

All the best,
Shay.




Please Use TryParse and Avoid Parse+Try/Catch

Recently I’ve run into a piece of class which was operating as the central place for type conversions in the system. While the idea of having such a class doesn’t sound like a problem, the way it’s been implemented definitely is.

Most of the conversion methods looked something like that:

public int ToInt(string value)
{
  try
  {
    return Int32.Parse(value);
  }
  catch
  {
    return DefaultValue;				
  }
}

I took this method for a test drive – I executed it within a loop and put a stopwatch before and after. The next chart demonstrates the results (X=number of loop iterations, Y = execution time in milliseconds):

Parse with try/catch execution time chart

100,000 calls to this ToInt method takes about 10 seconds!

This implementation would have been acceptable if there were no other solution for doing this stuff. But there is ALWAYS another way! and this time this way has a name – TryParse.

TryParse will achieve the same result like Parse but with one major difference – it will not raise an exception once the conversion is unsuccessful but instead it will return false. Changing the ToInt method implementation is quite easy:

public int ToInt2(string value)
{
  int result;
  if (!Int32.TryParse(value, out result))
  {
    return DefaultValue;
  }
  return result;
}

And now, when I re-run the test drive code I got blown away by the results – look at that chart:

TryParse execution time chart

The time for 100,000 conversions dropped from ~10 seconds to ~20 milliseconds! that is about 500% faster!!!

This is the joined chart, which makes the results crystal clear:

Joined results: TryParse vs Parse+try/catch

Conclusion

There is a single conclusion to this post: avoid using Parse+try/catch and start using TryParse. As simple as that.

All the best,
Shay.

kick it on DotNetKicks.com Shout it




Subscribe Subscribe

That's Me!

Hi! I'm Shay Friedman
I'm Shay Friedman - a Visual C#/IronRuby MVP, a consultant and instructor of .NET technologies, author, speaker and new technologies freak
More about me

Contact Me

> Contact page
> Twitter: @ironshay
> LinkedIn profile

Search

Hosted By

I'm hosting this site on Arvixe and I'm very happy with it.
If you're looking for ASP.NET hosting, I highly recommend it
(and if you order from this link I also get some beer money!)
Web Hosting