Search code examples
c#stringnullnullreferenceexceptionobject-reference

Why is a string assigned String.Empty seen as null (C#)?


I originally had some conditional code like this:

String _monthYr4;
. . .
if (_monthYr4.Length > 0)

...but when _monthYr4 was not assigned to prior to the conditional being reached, it blew up at run time, with the old chestnut, "Object reference not set to an instance of an object."

So I added what I thought was a default string value (albeit empty) to _monthYr4, like this:

private String _monthYr4 = String.Empty;

...but it still crashed in the exact same way. So I finally changed the conditional to this:

if (null != _monthYr4)

...and that works fine. But why? Shouldn't _monthYr4 be non-null, after assigning String.Empty to it?

On a side note, before I assigned String.Empty to _monthYr4, it looked like this:

String _monthYr4;

...but after I assigned String.Empty to _monthYr4, Visual Studio (or Resharper, maybe?) automagically prepended a "private" part so that it is:

private String _monthYr4 = String.Empty;

...but I don't know why.


Solution

  • Likely something is assigning null to that variable later on. Use ReSharper to find all references (Shift-F12) of _monthYr4, and make sure that all the write accesses can't assign null.