13
Is there any glaring difference between them? Whether in performance or ways of dealing, what are their particularities? What would be the correct way to use (if there is any difference)?
13
Is there any glaring difference between them? Whether in performance or ways of dealing, what are their particularities? What would be the correct way to use (if there is any difference)?
14
The first is used when you want to explicitly convert an object to a string. The second is to take the textual representation of an object. It is an important semantic difference that must be observed, even if the result turns out to be the same. And nothing guarantees that it is the same.
You can apply the Convert.ToString()
in a null value the method will know what to do, returning a string empty ""
). Already trying to use objeto.ToString()
it is possible that an exception NullReferenceException
be launched. However, this is not guaranteed. It may be that the specific type has some processing due even within the instance method ToString()
.
The conversion method tries to use the interface methods IFormattable
or IConvertible
, when available, before calling the textual 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 on 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);
}
Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.
9
There is a difference, yes... the correct thing is to use the Convert.ToString()
taking into account that he has treatment for values null
, as long as the .ToString()
nay..
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 a exception
untreated: NullReference
.
If I do: Console.Write(Convert.ToString(teste));
Return will be "nothing" (will print an empty string) - but will not launch exception
.
Browser other questions tagged c# .net string type-conversion
You are not signed in. Login or sign up in order to post.