Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialized readonly field is null, why?

Tags:

c#

Can anyone please explain, why private readonly Int32[] _array = new[] {8, 7, 5}; can be null?

In this example, it works, and _array is always not null. But in my corporate code I have a similar code and _array is always null. So I forced to declared it as static.

The Class is a partial Proxy Class from my WCF Contract.

using System;
using System.ComponentModel;

namespace NullProblem
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var myClass = new MyClass();

            // Null Exception in coperate code
            int first = myClass.First;
            // Works
            int firstStatic = myClass.FirstStatic;
        }
    }

    // My partial implemantation
    public partial class MyClass
    {
        private readonly Int32[] _array = new[] {8, 7, 5};
        private static readonly Int32[] _arrayStatic = new[] {8, 7, 5};

        public int First
        {
            get { return _array[0]; }
        }

        public int FirstStatic
        {
            get { return _arrayStatic[0]; }
        }
    }

    // from WebService Reference.cs
    public partial class MyClass : INotifyPropertyChanged 
    {
        // a lot of Stuff

        #region Implementation of INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
    }

}
like image 472
Martin Seidensticker Avatar asked Nov 08 '12 14:11

Martin Seidensticker


2 Answers

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};
}
like image 171
Marc Gravell Avatar answered Nov 04 '22 10:11

Marc Gravell


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 a 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;
    }
}
like image 20
W0lfw00ds Avatar answered Nov 04 '22 10:11

W0lfw00ds