0

I have the following static class with a static field:

public static class IncludeExtender {

  private static readonly MethodInfo _include = typeof(EntityFrameworkQueryableExtensions).GetTypeInfo();

}

Is there any difference between the previous example and the following one where the field value is defined in the class constructor?

public static class IncludeExtender {

  private static readonly MethodInfo _include;

  static IncludeExtender() {
    _include = typeof(EntityFrameworkQueryableExtensions).GetTypeInfo();
  }

}

What would be the best option for this?

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481

1 Answers1

1

No, they are identical. The readonly-modifier states that the members value might be changed only during object-intialization. That´s either directly within the class´-body or in the constructor.

However by initialising the variable within the constructor you may add further logic in front that affects the value, for example you can change the value depending on a certain condition. See this:

static IncludeExtender() {
    var a = "Test";
    _include = a.GetType().GetTypeInfo();
  }
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
  • 4
    Not quite true, If the constructor does not run then the former example will not execute, where as the latter runs before the constructor ever runs. – Jay Jul 18 '16 at 15:44
  • @Jay The static constructor will definitly run if you´re referencing the class in any way. So both will produce the same. – MakePeaceGreatAgain Jul 18 '16 at 15:48
  • Think about that... if you OOM how will it run? Further more then member which was allocated outside may or may not be allocated. – Jay Jul 18 '16 at 15:50
  • Also it's possible to change a `readonly` field more than once during initialization. It only guarantees that the field won't be modified after the static constructor has (or would have) been executed. – Kyle Jul 18 '16 at 15:53
  • 1
    @Kyle Yea, you´re right, I´ve updated this. – MakePeaceGreatAgain Jul 18 '16 at 15:54
  • They ARE NOT IDENTICAL! Especially when utilized from multiple threads! – Jay Jul 18 '16 at 16:13