Initialized readonly field is null, why?

WCF does not run the constructor (which includes the field initializer), so any objects created by WCF will have that null. You can use a serialization callback to initialize any other fields you need. In particular, [OnDeserializing]:

[OnDeserializing]
private void InitFields(StreamingContext context)
{
    if(_array == null) _array = new[] {8, 7, 5};
}

I recently ran into this issue too. I had an non-static class with static readonly variables, too. They always appeared null. I think it's a bug.

Fix it by adding an static constructor to the class:

public class myClass {
    private static readonly String MYVARIABLE = "this is not null";

    // Add static constructor
    static myClass() {
       // No need to add anything here
    }

    public myClass() {
       // Non-static constructor
    }

     public static void setString() {
       // Without defining the static constructor 'MYVARIABLE' would be null!
       String myString = MYVARIABLE;
    }
}

Tags:

C#