5

In C# 4, the behavior of types without the beforefieldinit flag was changed, so now a type initializer can call before first use of any static field of the class.

My questions are why has the C#/.NET team changed that behavior? What is the main reason? Can you show any practical example where this change makes any sense?

g t
  • 6,576
  • 6
  • 44
  • 83
weqew q
  • 271
  • 2
  • 9
  • Reference? Where did you read this? – leppie Jul 18 '11 at 07:34
  • 1
    I read it here: [link](http://msmvps.com/blogs/jon_skeet/archive/2010/01/26/type-initialization-changes-in-net-4-0.aspx) And in my oppinion the main reason is perfomance of extension methods? What do you think? – weqew q Jul 18 '11 at 07:36
  • 1
    Irrelevant. These things are undocumented for a reason. – Cody Gray Jul 18 '11 at 07:48

1 Answers1

12

The behaviour has always been within the bounds of what's documented - it's just that it changed from being eager to lazy in .NET 4.

I suspect the JIT team managed to find a way to make it lazy without a performance penalty... or possibly it helps performance somewhere else. This is likely to only be one such change in behaviour within the .NET 4 CLR vs the .NET 2 CLR... it happens that I noticed it, but I doubt that many other people did. I think it's entirely reasonable for the JIT team to adjust things as they see fit, within the documented guarantees.

Ultimately, if this makes your code fail, you've got a bug already.

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
  • Thank for your answer! Do you know how JIT compiler call type initialazers? Its compiles a method with call of a type initialazer twice or not? I mead that before first call I have a perfomance lack while method executes, but second call of the methods has normal perfomance. – weqew q Jul 18 '11 at 07:57
  • @Smeliy: I don't know, to be honest. I would expect there to be some sort of thunking going on, but I've always left the details to the JIT team :) – Jon Skeet Jul 18 '11 at 07:59