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
}
}
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]: