5

I am new to C#. Why are there multiple different ways to convert types? .ToString(), Convert.ToString, and (String), for instance. What are the differences and when should each of them be used?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Xdrone
  • 781
  • 1
  • 11
  • 21
  • It's a duplicated question [http://stackoverflow.com/questions/1170756/casting-vs-converting-an-object-tostring-when-object-really-is-a-string](http://stackoverflow.com/questions/1170756/casting-vs-converting-an-object-tostring-when-object-really-is-a-string) – Tarec Aug 18 '13 at 22:21

4 Answers4

4

These are not all casting - specifically, only (String) is a cast; the other two are regular methods.

  • ToString is a method of System.Object inherited by all objects in .NET. This method lets you provide a string representation of your object suitable for debugging purposes.
  • Convert.ToString is a group of more than thirty static method overloads. They provide string representations for various primitive types. Some overloads take a format provider, while other ones implicitly use the default one. If you pass a custom object to Convert.ToString, the implementation would first try going for IFormattable or IConvertible implementation in the object, if it has one. If it does not, the "catch all" ToString method of the object is called.
  • (String) is a cast: given an instance of a String assigned to a variable of type object or returned from a method with the return type of object, a cast lets you obtain a variable that is statically typed as a string. You can use such a string object to call string's instance methods on it, or to pass it to a method requiring a string.
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 2
    Also note that `Convert.ToString(crazyObject)` will check if the object implements `IConvertible`, or else if it implements `IFormattable`. It will use these interfaces if applicable. But as a last solution, it will simply do `((object)crazyObject).ToString()`. So in almost all cases, `Convert.ToString(crazyObject)` ends up doing the same as `crazyObject.ToString()`, but the latter is faster (not checking for interfaces). – Jeppe Stig Nielsen Aug 18 '13 at 22:40
1

The first two approaches in your question do not convert a type into a String but rather return a String that represents the type.

Your third option will tell the compiler to try and convert the casted object into a String.

Here's an explanation of each approach, I advise using one of the first because they have better design principles and are easier for other programmers to understand.

  1. toString()

toString() returns a String representation of the class. Every class has a method for toString() as it is inherited from the base Object class.

Consider the class below.

using System;
using People;
namespace People {
    class Person {
        boolean male = false;
        int age = 17;
    }
}

If you had a Person object and called toString() on it it would return a String with the following contents: People.Person

This is because it is calling Object.toString() which simply returns the namespace and class name of the Object.

If a class were to override toString() (which is a very common case), it is up to the programmer to define a String representation of the class.

using System;
using People;
namespace People {
    class Person {
        boolean male = false;
        int age = 17;
        public override String toString() {
             return "Gender: " + (male ? "Male : "Female") + "\tAge: " + age;
        }
    }
}

Now that toString() has an implementation it'll return "Gender: Male Age: 17". It is important to remember that toString() doesn't convert an object, but merely returns a String that someone defined to describe the objet.

Primitives can also have toString() invoked on them too

int i = 3;
String str = i.toString();  // "3"
  1. Convert.toString(some type)

Convert.toString() returns a String representation of a type. This method is useful for primitives that you want to represent a String value for.

Given the following code:

int i = 7;
double d = 4.3;
String stringVersions[] = {Convert.toString(i), Convert.toString(d) };

I inflate an array of strings with two separate types of primitives. The array itself looks like: ["7", "4.3"].

Convert.toString() also has overloads for various formatting options which is functionality that a simple call to .toString() lacks.

  1. Casting an Object to a String

Casting an object to a String is only useful if you know that the Object you're dealing of is an instance of a String and you'd like to treat it as a String object. Technically this approach will work in C#, however it is a poor design choice as it is implying that the casted String is a complete representation of the int, which isn't true in this case, instead your desire is to simply work with a different type. For that reason, and the fact that it might be easier for other programmers to interpret toString() or Convert.toString() you probably shouldn't default to using this option.

String age = (String) 4;
deadboy
  • 849
  • 2
  • 9
  • 28
0

.ToString() is meant as a string representation of an object, it is not a cast like (String). The latter is used to actually convert the object to a string. It differs from as where the former will throw an exception when the convert fails, and the latter will instead return a null value.

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
0

ToString is a method derived from the Object Class, and each class can override this method. For example you can write a class representing a user. It is a User, not a string, but you can define a Method ToString so you can precise how it should be displayed by text (for example you can return the first name and the last name of the user).

But if you try to cast your user Object using (String) you will get an error because The class user is not a derivated class of the class String.

Convert.ToString Only accept primitives types so you couldn't use it with a custom Class.

Hopes it answer your question.

DARK_DUCK
  • 1,727
  • 2
  • 12
  • 22