String casts in .NET

后端 未结 9 1043
死守一世寂寞
死守一世寂寞 2021-02-15 02:21

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.

相关标签:
9条回答
  • 2021-02-15 03:20

    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.

    0 讨论(0)
  • 2021-02-15 03:20

    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);
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-15 03:21

    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";
        }
    }
    
    0 讨论(0)
提交回复
热议问题