The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Email Subscription

    Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 716 other subscribers

Delphi and C# compiler oddities

Posted by jpluimers on 2013/01/08

When developing in multiple languages, it sometimes is funny to see how they differ in compiler oddities.

Below are a few on const examples.

Basically, in C# you cannot go from a char const to a string const, and chars are a special kind of int.

In Delphi you cannot go from a string to a char.

Delphi

[sourcecode language=”pascal”]
program CompilerOddities;

{$APPTYPE CONSOLE}

{$R *.res}

uses
System.SysUtils;

type
CharAndString = class
const A = string(‘A’);
const B = string(‘B’);
const AB = A + B;
const IJK = ‘IJK’; // automatically a string
const X = ‘X’; // Unicode/ASCII 88
const Y = ‘Y’; // Unicode/ASCII 89
const Value: Integer = Integer(X) + Integer(Y); // Char is not Integer, but you can cast it: 177
const XY = string(X + Y);
const YX = string(Y + X);
const I = IJK[1]; // E2026 Constant expression expected
end;

begin
end.
[/sourcecode]

C# (changeset)

[sourcecode language=”csharp”]
namespace CompilerOddities
{
public class CharAndString
{
public const string A = "A";
public const string B = "B";
public const string AB = A + B;
public const string IJK = "IJK";
public const char X = ‘X’; // int 88
public const char Y = ‘Y’; // int 89
public const int Value = X + Y; // because char is actually int with a special syntax: 177
// these don’t compile:
public const string XY = X + Y; // Cannot implicitly convert type ‘int’ to ‘string’
public const string YX = Y.ToString() + X.ToString(); // The expression being assigned to ‘CompilerOddities.CharAndString.YX’ must be constant
public const char I = (char)(IJK[0]); // The expression being assigned to ‘CompilerOddities.CharAndString.A1’ must be constant
}
}
[/sourcecode]

–jeroen

/ASCII

Leave a Comment