Are there any glaring differences between them? Whether in performance or ways of treating, what are their particularities? What would be the correct way to use it (if there is any difference)?
Are there any glaring differences between them? Whether in performance or ways of treating, what are their particularities? What would be the correct way to use it (if there is any difference)?
The first one is used when you want to explicitly convert an object to a string . The second is to get the textual representation of an object. It is an important semantic difference that must be observed, even if the result ends up being the same. And nothing guarantees that it is the same.
You can apply Convert.ToString()
in a null value that the method will know what to do, returning an string empty ""
). Already attempting to use objeto.ToString()
it is possible for a NullReferenceException
exception to be thrown. But this is not guaranteed. It may be that the specific type has some due treatment even within the instance method ToString()
.
The conversion method attempts to use the methods of the interfaces IFormattable
or IConvertible
, when available, before calling the text representation of the object.
The ToString()
is available for any object. The conversion method is only available for some specific data types (see the list in the link above).
Functional example showing all situations:
int? x = null;
int y = 10;
string z = null; //só como exemplo, não faz sentido converter string p/ string
try {
WriteLine($"Convert.ToString(x) = {Convert.ToString(x)}"); //fica nada
WriteLine($"Convert.ToString(y) = {Convert.ToString(y)}"); //fica 10
WriteLine($"Convert.ToString(z) = {Convert.ToString(z)}"); //fica nada
WriteLine($"x.ToString() = {x.ToString()}"); //fica nada
WriteLine($"y.ToString() = {y.ToString()}"); //fica 10
WriteLine($"z.ToString() = {z.ToString()}"); //dá a exceção
} catch (Exception ex) { //não faça isto, só coloquei para facilitar o teste
WriteLine("Falhou");
WriteLine(ex);
}
See running dotNetFiddle .
It has a difference yes ... the most correct is to use Convert.ToString()
considering that it has treatment for null
values, while .ToString()
does not.
When you use .ToString()
you start from the principle that you are working with a non-null object, correct?
Practical example:
static void Main(string[] args)
{
var teste = "" ;
teste = null;
Console.Write(teste.ToString());
Console.ReadLine();
}
Will result in% unhandled%: exception
.
If I do: NullReference
The return will be "nothing" (it will print an empty string) - but will not cast Console.Write(Convert.ToString(teste));
.