Thursday, July 24, 2008

Still bugs in the C# compiler.

I have been putting together some simple training for VB6 developers who have had little or no experience with C# or object orientation and I found this lovely bug in the compiler.

Speaking with a friend who works for Microsoft he quickly said it wasn't a bug and gave me a line about explicit casting and method selection in the compiler but I think that the example is really simple and is a clear breach of overloading principles.

I have a base class with a virtual method which contains an integer parameter. In a derived class I include both an override for the original method plus an overload for the same method but this time having a float parameter.

The main function calls the derived class and even when the parameter is cast explicitly to int, the int overload is never called.

This is true in the 2005 and 2008 versions.

To prove a point I wrote the exact equivalent functionality in VB.net and it works as expected.

Here's the code.

class Program

{

static void Main(string[] args)

{

DerivedClass dc = new DerivedClass();

dc.AMethod((int)1);

dc.AMethod(1f);

Console.ReadKey();

}

}

class BaseClass

{

public virtual void AMethod(int i)

{

Console.WriteLine("Base class integer parameter!");

}

}

class DerivedClass : BaseClass

{

public override void AMethod(int i)

{

Console.WriteLine("Derived class integer parameter");

}

public void AMethod(float f)

{

Console.WriteLine("Derived class float parameter");

}

}

No comments: