Question

Just a simple observation. The property MethodBase.IsConstructor does not work with static constructors, and the documentation does not mention this fact (quote: "true if this method is a constructor represented by a ConstructorInfo object").

Sample:

static class Program
{
  static void Main()
  {
    ConstructorInfo ci = typeof(Test).GetConstructor(
        BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { }, null);
    Console.WriteLine(ci is ConstructorInfo); // silly; writes True
    Console.WriteLine(ci.IsConstructor);      // ??     writes False
  }
}

static class Test
{
  static Test()
  {
    Console.WriteLine("I am your static constructor");
  }
}

Question: Why? Bug or incomplete specification?

Was it helpful?

Solution

"Static constructor" is really just C# terminology. In .NET itself, there's a type initializer (as per Type.TypeInitializer). A type can have a type initializer without having a static constructor declared in C# - e.g. for static variable initialization.

Having a static constructor in the source C# has two effects:

  • It removes the beforefieldinit flag from the type, potentially changing timing
  • It adds the code into the type initializer

So while it's represented by a ConstructorInfo, I'm not particularly surprised that IsConstructor returns false, in that it's not a constructor in CLR terminology. It's a non-constructor represented by a ConstructorInfo object :) It would certainly be clearer if the documentation were reworded to "if this method is an instance constructor" - and also if GetConstructor didn't return it (as that's pretty inconsistent, IMO).

Addmittedly the docs for GetConstructor do state:

To get the class initializer (.cctor) using this method overload, you must specify BindingFlags.Static | BindingFlags.NonPublic. You can also get the class initializer using the TypeInitializer property.

... so they're not calling it a constructor there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top