Micah Zoltu
Micah Zoltu

Reputation: 7422

Why does resharper think a private readonly variable can be null?

In the following code, Resharper 8 tells me that _myClasses has a "Possible 'System.NullReferenceException'". Is this a bug in Resharper or is there something I am missing about how this code will work? My understanding is that the readonly modifier makes it so I can only set _myClasses once and the one thing I am setting it to is an instance of something. What scenario could this be null?

private readonly IList<MyClass> _myClasses = new List<MyClass>();

void Foo()
{
    _myClasses.Clear(); // Possible 'System.NullReferenceException'
}

Upvotes: 1

Views: 337

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

readonly means "can't change after constructor is completed". So any constructor can change its value to null (now or future written constructor).

...assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.

Sample:

class Foo
{
  private readonly string myClasses = "test";

  public Foo(int value) {  }    
  public Foo(string text) {  myClasses = text;}    
  public Foo() 
  {
     myClasses = null;
     Bar();
  }

  void Bar()
  {
    if (myClasses == null)
    {
     Console.WriteLine("Null???");
    }
  }
}

In sample above Foo() constructor will set myClasses to null and case exception if one relies on this value not be null.

Upvotes: 3

Related Questions