5

I have a static class with a static field that is initialized in place:

private static SomeType _instance = new SomeType();

This code is a part of a portable class library that is used on multiple platforms. Everything works fine on desktop platforms, but when compiled for Windows Phone 8 the _instance is null. But if I move the initialization to a default static constructor, the _instance is initialized properly.

I tried to search for an explanation of this behavior but haven't found anything that would explain it.

UPDATE. I spent some time trying to create a repeatable sequence of steps to reproduce the error, but at some point error no longer occurred even when I switched back to the original code. I came to conclusion that this was a false alarm and the problem was apparently caused by something else. I don't feel comfortable to leave it without explanation, but so far I have no grounds to believe that this has to do with static field initialization.

Vagif Abilov
  • 9,835
  • 8
  • 55
  • 100
  • 1
    Might actually be a bug, have you tried raising a Connect ticket for it? – Adam Houldsworth Aug 15 '14 at 14:55
  • 3
    I guess it might have been set to `null` somewhere. Just add `readonly` keyword and see issue is still there? – Sriram Sakthivel Aug 15 '14 at 15:13
  • Spent more time on it. Didn't manage to create a repeatable scenario. Most likely this was a false alarm. If this happens again, I will update the post. – Vagif Abilov Aug 16 '14 at 12:14
  • 1
    possible duplicate of [Is the order of static class initialization in C# deterministic?](http://stackoverflow.com/questions/3681055/is-the-order-of-static-class-initialization-in-c-sharp-deterministic) – Eugene Podskal Aug 18 '14 at 11:33
  • 1
    Vagif, have you tried @Sriram's suggestion? If you add readonly you will immediately get a compiler error if there is any other code that could possibly change the value of the field. – chiccodoro Aug 19 '14 at 11:43
  • Also, you have not written *where* in your code you evaluated the field and got `null`. Could it be in a static field initializer or a static constructor? If so, @Eugene's link might be relevant. – chiccodoro Aug 19 '14 at 11:51
  • @chiccodoro, yes I tried Sriram's suggestion. As I wrote in the update to the post, I can no longer reproduce the error and came to the conclusion that this was a false alarm. – Vagif Abilov Aug 20 '14 at 05:28
  • Does that static field must be initialized during a deserialization process ? Because for example DataContractSerializer doesn't pass by the construction process. – Mickael Thumerel Oct 25 '16 at 06:56

1 Answers1

0

You need to make sure that nothing else is updating the static value, as static properties will get initialized as the app domain is created.

Samer Aburabie
  • 248
  • 2
  • 8