Home > General > Casting and converting to strings

Casting and converting to strings

One thing that makes me nervous while looking through a code base is the liberal use of the ToString() method everywhere. There are a couple different ways to convert/cast to a string:

Explicit cast:

string str = (string)someObj;

ToString() method:

string str = someObj.ToString();

Convert.ToString() method:

string str = Convert.ToString(someObj);

as operator:

string str = someObj as string;

Explicit casts should be used at times when you are sure that someObj is a string. It also doubles as an assertion since an InvalidCastException will be thrown at runtime if the cast fails. The result will be null if attempting to cast a null object.

The ToString() method returns the string representation of an object. If someObj is null, a NullReferenceException will be thrown.

The Convert.ToString() method behaves differently depending on the type of object passed to the method. When an object is passed to the method, it calls the ToString() method on the object:

public static string ToString(Object value) 
	return ToString(value, null);

public static string ToString(Object value, IFormatProvider provider) 
	IConvertible ic = value as IConvertible; 
	if (ic != null)
		return ic.ToString(provider); 
	IFormattable formattable = value as IFormattable;
	if (formattable != null)
		return formattable.ToString(null, provider);
	return value == null ? String.Empty : value.ToString(); 

When a string is passed to the Convert.ToString(), it simply passes through:

public static String ToString(String value) 
	Contract.Ensures(Contract.Result<string>() == value);
	return value; 

This is important to remember because if a null object is passed to the Convert.ToString() method, an empty string is returned. However, if a null string is passed to the method, a null is returned.

The as operator provides a way to cast an object without throwing an exception if the cast fails. If a cast fails, the result will be null.

  1. March 14, 2012 at 11:10 am

    I always have a ToStringSafe extension method

    public static string ToStringSafe(this object input)
    return input != null ? input.ToString() : string.Empty;

  1. No trackbacks yet.

Leave a Reply to dotnetchris Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: