3

I have code like this.

string b=null;
string a = Convert.ToString(b);

Ref from:

Checking for null before ToString()

But while i convert b to string i get only null value not empty string.but some days ago i have also done null coversion using same convert.tostring(). at that it works fine but now not working. i am rotating my head here and there pls help me why this is happening? only thing is that i worked in 3.5 framework but now 4.0 .

Community
  • 1
  • 1
Vetrivel mp
  • 1,214
  • 1
  • 14
  • 29

3 Answers3

5

Convert.ToString(string) will return the string unchanged. This is true of every version of the framework, as per the documentation:

You are mistaken that calling Convert.ToString((string)null) ever returned anything except null. What you were probably calling was Convert.ToString((object)null). This will return empty-string.

string a = Convert.ToString((object)null);
string b = Convert.ToString((string)null);
// a now equals string.Empty, but b equals null.

You could cast string b to an object as I have done, but I would suggest you use the null-coalescing operator instead:

string a = b ?? string.Empty
RB.
  • 36,301
  • 12
  • 91
  • 131
0

Try this :

string a = (b == null) ? string.Empty : b;

Ebad Masood
  • 2,389
  • 28
  • 46
0

When we are doing any Conversion's try to check whether it is null or not.

Try to do like this

if(!String.IsNullOrEmpty(b))
{
string c=Convert.ToString(b);
}
Hemant Kumar
  • 4,593
  • 9
  • 56
  • 95