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.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Convert.ToString(obj)Converts the specified value to its equivalent String representation. Will return
String.Emptyif specified value isnull.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)objIt’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
nullif the object isnull AND of type String or of type which implements custom cast to string operator. See examples.obj as stringSafe cast operation. Same as above, but instead of throwing an exception it will return
nullif cast operation fails.Hint: Don't forget to use CultureInfo with
obj.ToString()andConvert.ToString(obj)Example:
Here is an example of custom cast operator:
public class Test { public static implicit operator string(Test v) { return 'test'; } }