Why are these three cases markes with possible NullReferenceException
Why are these three cases markes with possible NullReferenceException:
using System;
namespace WhyPossibleNullReference
{class SampleClass
{private static readonly object TestObject1 = new object();
private readonly object testObject2 = new object();
private readonly object testObject3;
public SampleClass(object testObject3)
{if (testObject3 == null)
throw new ArgumentNullException("testObject3");this.testObject3 = testObject3;
}
public void DoSomething()
{// case 1:
// why is the object here marked with "possible NullReferenceException"?
// the static constructor should be called before this method and thus the field is initialized
Console.WriteLine(TestObject1.ToString());
// case 2:
// why is the object here marked with "possible NullReferenceException"?
// the field is set before the constructor is called thus the field is initialized
Console.WriteLine(testObject2.ToString());
// case 3:
// why is the object here marked with "possible NullReferenceException"?
// the field is set in the constructor and a null check made sure that it is not set to null
Console.WriteLine(testObject3.ToString());
}
}
}
Please sign in to leave a comment.