Convert.ToString bug?

  • Thread starter Thread starter William Stacey
  • Start date Start date
W

William Stacey

Example line:
string temp = Convert.ToString(null);

Convert.ToString() says it will return empty string if null is passed as
parm. This returns a null. Is this oversight in the Convert method?

What is the way you guys are checking for nulls on string parms and triming
if they pass something other then null. I was thinking this would do in
most cases, but does not because of "error above"

private void testnull(string test)
{
test = Convert.ToString(test).Trim(); //one line would be nice.
if ( test == null ) //would rather check for "test" equals "" here, then
have to test for null first and then do a trim().
MessageBox.Show(this, "test2 is null.");
else
MessageBox.Show(this, "test2 is not null.");
}

--wjs
 
William,
Convert.ToString(string) is defined to return the object that you pass. If
you pass null to this function you get null back.

Convert.ToString(object) is defined to return the string representation of
the object you pass. If you pass null to this function you get String.Empty
back.

In your function, you are passing test as a string, so the first function is
going to be called.

Hope this helps
Jay
 
Jay B. Harlow said:
Convert.ToString(string) is defined to return the object that you pass. If
you pass null to this function you get null back.

Convert.ToString(object) is defined to return the string representation of
the object you pass. If you pass null to this function you get String.Empty
back.

In your function, you are passing test as a string, so the first function is
going to be called.

Just to demonstrate that:

using System;

public class Test
{
static void Main()
{
string x = Convert.ToString ((string)null);
Console.WriteLine (x==null); // Prints true
x = Convert.ToString ((object)null);
Console.WriteLine (x==null); // Prints false
}

}
 
Back
Top