Wednesday, March 31, 2010

Where C# fails, VB delivers.

Recently I've came across a strange behavior that took me some thinking to work around.

As you may know, my language of choice has been VB for as long as I can remember. However, I, like any good developer, can work just as good in C#. Really, it's no biggie.

Anyway, what I'm talking about here is dynamic type resolution.

For instance let's say we have the following VB program:

Module Program
  Sub Main()
    Dim value As Object = 123
  End Sub

  Sub Format(ByVal value As IFormattable)
    Console.WriteLine(value.ToString(Nothing, Nothing))
  End Sub
End Module

When ran, the above program will generate the following output:


Easy enough, huh?

Now, if we port this program to C# like this:

class Program
  static void Main(string[] args)
    object value = 123;
  static void Format(IFormattable value)
    Console.WriteLine(value.ToString(null, null));

Which is the literal translation of the VB program above, we can't even compile to program, because the C# compiler gives the following errors:

error CS1502: The best overloaded method match for 'DynamicCS.Formatter.Format(System.IFormattable)' has some invalid arguments

error CS1503: Argument '1': cannot convert from 'object' to 'System.IFormattable'

It's the same damn code, how come C# can't convert from object to IFormattable?

Well, the answer is that the C# compiler requires that all types to be known at compile time, rater than establish at runtime.


Post a Comment