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;
 
That is basically the same thing as string var1 = "".

Regards,
Joakim
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top