Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are there different ways to convert types in C#?

Tags:

c#

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?

like image 277
Xdrone Avatar asked Aug 18 '13 22:08

Xdrone


2 Answers

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.
like image 172
Sergey Kalinichenko Avatar answered Oct 25 '22 06:10

Sergey Kalinichenko


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;
like image 44
deadboy Avatar answered Oct 25 '22 04:10

deadboy