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 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With