Stefan Glienke deleted his post about parameterless record constructors, presumably due to all the off topic comments. The question was why the Delphi language does not allow parameterless constructors.

Stefan Glienke deleted his post about parameterless record constructors, presumably due to all the off topic comments. The question was why the Delphi language does not allow parameterless constructors.

Anyway, just before he deleted it I wondered if the answer could be found by looking at .net. I wondered if many of the enhancements to old style records came about due to the .net Delphi compiler trying to map onto .net functionality.

Anyway, it turns out that .net at CLR level does allow parameterless constructors on structs. But the C# language bans them: https://msdn.microsoft.com/en-us/library/saxz13w4.aspx

Jon Skeet posted an answer on SO way back in 2008 on this topic: http://stackoverflow.com/a/333840/ From that answer:

----
The CLR allows value types to have parameterless constructors, but C# doesn't. I believe this is because it would introduce an expectation that the constructor would be called when it wouldn't. For instance, consider this:

MyStruct[] foo = new MyStruct[1000];

The CLR is able to do this very efficiently just by allocating the appropriate memory and zeroing it all out. If it had to run the MyStruct constructor 1000 times, that would be a lot less efficient. (In fact, it doesn't - if you do have a parameterless constructor, it doesn't get run when you create an array, or when you have an uninitialized instance variable.)

The basic rule in C# is "the default value for any type can't rely on any initialization". Now they could have allowed parameterless constructors to be defined, but then not required that constructor to be executed in all cases - but that would have led to more confusion. (Or at least, so I believe the argument goes.)
----

My guess is that Embarcadero decided to ban parameterless constructors on Delphi records for the same reason. Or perhaps they just copied the rules from C# without realising that the CLR supported parameterless struct constructors.
https://msdn.microsoft.com/en-us/library/saxz13w4.aspx

Comments

  1. I don't buy the inefficiency either. C++ will call the constructor for each element of an array.

    ReplyDelete
  2. Was that the post that wandered off into centralised v decentralised source control? I wondered where that went... was quite interesting.

    ReplyDelete
  3. No, Richard Stevens , it was not that post, that was a different one

    ReplyDelete

Post a Comment