A site devoted to discussing techniques that promote quality and ethical practices in software development.

Monday, March 5, 2007

Bug in Delphi.Net in handling class function of Char

Every time, when I tried to do some .Net programming in Delphi, I often run into compiler and/or runtime bug by Delphi.Net (D2006) and it is getting to the annoying point. I must have missed something. Should I simply program Delphi as if .Net does not exist? If I do that would I have better experience? Weird!

I did not discover this bug but I was asked why one needs an object instance to use Char's class procedure or function (in C#, they are known as static function or in UML, they are the classified function).

At first, I did not know the answer thinking that Delphi.Net may be using TChar or something like that. On deeper investigation, there is no such type in Delphi.Net.

So I cooked up a sample application so that I can examine the IL code it generates - very important when dealing with Delphi.Net output. As previously blogged, while Borland can spin its own flavour, but ultimately at run time, it has to obey the CLR.

System.Char in .Net is a structure containing mostly static methods and by definition these methods can be accessed without the need to use an object instance.

The following code fragment illustrates the compiler bug:

00000001 var
00000002 c : System.Char;
00000003 cc : Char;
00000004 b : system.Boolean;
00000005 begin
00000006 c := 'a';
00000007 cc := 'b';
00000008
00000009 Console.WriteLine( 'Is it a Char? ',
00000010 System.Char.IsLetter( c ).ToString() );
00000011 Console.WriteLine( 'Type of cc is {0}',
00000012 cc.GetType().AssemblyQualifiedName );
00000013 Console.WriteLine( 'Type of Char is {0}',
00000014 Typeof(Char).AssemblyQualifiedName );
00000015 Console.WriteLine( 'Char is {0}', cc.ToString() );
00000016 // b := Char.IsLetter( 'b' );
00000017 end;
Here is the output from the above code fragment:

Result:
Is it a Char?
Type of cc is System.Char, mscorlib, Version=1.0.5000.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089
Type of Char is System.Char, mscorlib, Version=1.0.5000.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089
Char is b
If you uncomment Line 16 above, the code fragment will not compile complaining that it needs a object reference. Lines 11 & 13 clearly shows that Delphi.Net's Char is simply System.Char and hence it should allow the syntax in Line 16 to be used.

Insisting on having a object reference just to use static method is just plain wrong!

Another tip for using Delphi.Net, when in doubt, always print out the Type.AssemlyQualifiedName as Delphi.Net has a habit of giving you this Borland Special Treatment.

As my colleague said, Char is one of the most basic thing in any programming language, why can Borland handle this without error? I am not a Borland employee and I do not have an answer for that other than to tell him that it is another Delphi.Net compiler bug.

No comments:

Blog Archive