views:

330

answers:

2

What is the real difference between a C# static constructor and a Java static block?

They both must be parameterless. They are both called only once, when the related class is first used.

Am I missing something, or are they the same thing, just with different names?

+4  A: 

They are equivalent, except that a C# class can only have one static constructor (plus static field initializers).

Also, in C#, a static constructor will apply the beforefieldinit flag.

SLaks
Obviously Java is not going to apply any beforefieldinit flags, as it isn't compiled to MSIL.
Joren
@Joren: I realize that. However, it is a difference in the behavior of the two features.
SLaks
Yes, but my (not so explicit, I admit) point was: It might be more useful to explain the difference in terms of the code semantics (i.e. order of field initialization and the static constructor) than in terms of implementation details. (Especially when it's details that don't even have any meaning for one of the two languages being considered.)
Joren
Would you both agree that if one was converting Java code to C#, that there would exist no risk of losing functionality?
Mackenzie
@Mackenzie: As long as the code doesn't have side effects that must be run lazily (or not), it should be equivalent.
SLaks
Mackenzie
I thought java static blocks were executed when the class was loaded, not at the first use of the class (via a constructor or static method call). That's a subtle point since (iirc) classloaders will usually load all referenced classes at startup (so the static blocks will be executed immediately) but you can always load a class manually later. I have no idea how C# handles this.
bgiles
d'oh - a few hours after making that last comment I was skimming through "Effective Java, 2E" and came across that very issue. Java static blocks are only executed when the class is first used, not first loaded if they do any pre-loading.
bgiles
A: 

They are not.

In C#, there blocks can only hold constructors. In java you are able to execute statements.