Null question

  • Thread starter Thread starter Keith Smith
  • Start date Start date
K

Keith Smith

Are these two statements identical?

public static string Var1 = "";
public static string Var1 = null;

I read somewhere that there was a difference, but I haven't found it. Any
ideas?
 
In the first version, Var1 references a string with the value "".
In the second version, Var1 does not reference a string at all.

Regards,
Joakim
 
Keith said:
Are these two statements identical?

public static string Var1 = "";
public static string Var1 = null;

I read somewhere that there was a difference, but I haven't found it.
Any ideas?

Why on earth should these be identical?

The first line assigns the empty string (a live object) to Var1. The
second line assigns, um, nothing (i.e. no live object) to Var1.

So

Console.WriteLine(Var1);
Console.WriteLine(Var1.Length);
Console.WriteLine(Var1.GetHashCode());

will work fine for "", but will crash on the second line for null.


Cheers,
 
Keith Smith said:
Are these two statements identical?

public static string Var1 = "";
public static string Var1 = null;

I read somewhere that there was a difference, but I haven't found it. Any
ideas?

How about string var1 = string.Empty;
 
Back
Top