views:

573

answers:

9
+8  Q: 

String casts

Hi

Why is there so may ways to convert to a string in .net? The ways I have seen are .ToString, Convert.ToString() and (string). What is the Difference.

+5  A: 

Convert.ToString() will return an empty string if the object is null .ToString and (String) will throw an exception. Convert.ToString will internally call .ToString() if the value is null it will return an empty String.

cgreeno
+1 didn't know Convert.ToString() will handle null references that way. Good to know!
Dave Van den Eynde
+18  A: 

Convert.ToString(obj)

Converts the specified value to its equivalent String representation. Will return String.Empty if specified value is null.

obj.ToString()

Returns a String that represents the current Object. This method returns a human-readable string that is culture-sensitive. For example, for an instance of the Double class whose value is zero, the implementation of Double.ToString might return "0.00" or "0,00" depending on the current UI culture. The default implementation returns the fully qualified name of the type of the Object.

This method can be overridden in a derived class to return values that are meaningful for that type. For example, the base data types, such as Int32, implement ToString so that it returns the string form of the value that the object represents. Derived classes that require more control over the formatting of strings than ToString provides must implement IFormattable, whose ToString method uses the current thread's CurrentCulture property.

(string)obj

It's a cast operation, not a function call. Use it if you're sure that the object is of type string OR it has an implicit or explicit operator that can convert it to a string. Will return null if the object is null AND of type String or of type which implements custom cast to string operator. See examples.

obj as string

Safe cast operation. Same as above, but instead of throwing an exception it will return null if cast operation fails.


Hint: Don't forget to use CultureInfo with obj.ToString() and Convert.ToString(obj)

Example:

12345.6D.ToString(CultureInfo.InvariantCulture);          // returns 12345.6
12345.6D.ToString(CultureInfo.GetCultureInfo("de-DE"));   // returns 12345,6
Convert.ToString(12345.6D, CultureInfo.InvariantCulture); // returns 12345.6
Convert.ToString(12345.6D, CultureInfo.GetCultureInfo("de-DE"));  // 12345,6
Convert.ToString(test);  // String.Empty, "test" is null and it's type
                         // doesn't implement explicit cast to string oper.
Convert.ToString(null);  // null
(string) null;           // null
(string) test;           // wont't compile, "test" is not a string and
                         // doesn't implement custom cast to string operator
(string) test;           // most likely NullReferenceException,
                         // "test" is not a string,
                         // implements custom cast operator but is null
(string) test;           // some value, "test" is not a string,
                         // implements custom cast to string operator
null as string;          // null

Here is an example of custom cast operator:

public class Test
{
    public static implicit operator string(Test v)
    {
        return "test";
    }
}
Koistya Navin
object does not need to implement IConvertible.
Dave Van den Eynde
under "(string)obj" you say it will return null if the object is null, but it will actually throw a NullReferenceException.
Barry Fandango
@Barry, if object doesn't implement custom cast to string operator it just won't compile, otherwise it can throw an exception - depends on how exactly the type implements cast to string operator.
Koistya Navin
A: 

Think.

ToString is a virtual method, and each type can implement it however it wants. Also System.Object provides default implementations so that it always succeeds. Convert.ToString works only with nulls as well and allows you to use IFormat provier as noted in the comment.

Casting to string requires object to implement casting operator. Again, types can implement it however they like, but most types do not, so you may get an exception here.

Use .ToString as your best option.

Krzysztof Koźmic
Convert.ToString() will do any object, it'll simply call obj.ToString() if it's not null. But there is an overload for IFormatProvider.
Dave Van den Eynde
Right, thanks for the fix - I updated the answer.
Krzysztof Koźmic
A: 

ToString() is a method of object, and it will always work on a non-null reference, so you'll get something, but whether that something is what you want, is a different story.

Convert.ToString() will yield the same result in most cases, but isn't as flexible as Object.ToString() as you can't pass custom formatting rules.

(string) will cast your object to string, and if it isn't a string then you'll get an InvalidCastException().

Dave Van den Eynde
+1  A: 

Don't forget as string

Matt Grande
A: 

.ToString() is an instance method which asks the object for its string representation. When the object is null, this will throw a exception.

(string) is a cast to the string type, which isn't a very good idea in most cases except for simple data types, since it can break (throw an exception) when it's null or an invalid cast

Convert.ToString() does a bit more checking than a simple cast, giving a more robust alternative to the cast. It will return the empty string when the object is null.

Rik
+8  A: 
  • .ToString() can be called from any object. However, if the type you call it on doesn't have a good implementation the default is to return the type name rather than something meaningful about the instance of that type. This method is inherited from the base Object type, and you can overload it in your own types to do whatever you want.

  • (string) is a cast, not a function call. You should only use this if the object you need already is a string in some sense, or if you know there is a good implicit conversion available (like from int). This will throw an exception is the object cannot be converted (including when the object is null)

  • as string is another way to write (string), but it differs in that it returns null rather than throwing an exception if the cast fails.

  • Convert.ToString() attempts to actually convert the argument into a string. This is the best option if you don't really know much about the argument. It can be slow because it has to do a lot of extra work to determine what kind of results to return, but that same work also makes it the most robust option when you don't know very much about the argument. If nothing else is available, it will fall back to calling the argument's .ToString() method.

  • String.Format The string class' .Format method can also be used to convert certain types to strings, with the additional advantage that you have some control over what the resulting string will look like.

  • Serialization This is a little more complicated, but .Net includes a couple different mechanisms for converting objects into a representation that can be safely stored and re-loaded from disk or other streaming mechanism. That includes a binary formatter, but most often involves converting to a string in some format or other (often xml). Serialization is appropriate when you want to later convert the your string back into it's originating type, or if you want a complete representation of a complex type.

Joel Coehoorn
+2  A: 

object.ToString() is the most basic way of retrieving a string representation of an object, and can be specifically implemented by the object.

Convert.ToString() expands on that and provides some specific overloads for primitive types (char, byte, int, double, etc.) that allow for some more type-specific functionality (like base conversion, for example)

(string) is a casting operator, and will only work if the type is either a string or has an implicit or explicit operator that can convert it to a string. Otherwise you'll get an InvalidCastException

Adam Robinson
A: 

Not to nitpick but null is a valid value for a String object. Therefore (string) null does not throw any exceptions. Try it for yourselves:

using System;

namespace Test
{
    class Program
    {
     public static void Main(string[] args)
     {
      string s = (string) null;
      Console.WriteLine(s);
     }
    }
}
Sklivvz