Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert Null Value from convert.tostring()

Tags:

asp.net

c#-4.0

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 .

like image 272
Vetrivel mp Avatar asked Mar 29 '26 18:03

Vetrivel mp


1 Answers

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

  • 4.0
  • 3.5
  • 3.0
  • 2.0

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
like image 175
RB. Avatar answered Apr 02 '26 22:04

RB.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!