What is the difference between convert.ToString and ToString in C# full Explanation
In C#, there are two ways to convert an object or
value to a string representation: `Convert.ToString()` and `ToString()`. While
both methods achieve the same result, there are some differences between them.
Here's a full explanation of the differences:
1.
`Convert.ToString()`:
v `Convert.ToString()`
is a static method provided by the `Convert` class in C#.
v It
can be used to convert various data types, including primitive types, to their
string representations.
v If
the object being converted is `null`, `Convert.ToString()` returns an empty
string (`""`) rather than throwing an exception.
v It
handles `null` values, so it is safe to use even if the object being converted
is null.
v Example:
int num = 42;
string str1 = Convert.ToString(num); // "42"
string str2 = Convert.ToString(null); // ""
2.
`ToString()`:
v `ToString()`
is a method that is defined in the `Object` class, the base class for all types
in C#.
v It
is overridden by derived types to provide a specific string representation of
an object.
v The
behavior and result of `ToString()` can vary depending on the type of the
object.
v If
the object being converted is `null`, calling `ToString()` on it will result in
a `NullReferenceException`.
v Example:
int num = 42;
string str1 = num.ToString(); // "42"
string str2 = null;
string str3 = str2.ToString(); // Throws
NullReferenceException
3.
Customization and Overrides:
v The
`ToString()` method can be overridden in derived types to provide a custom
string representation based on the specific class's requirements.
v By
overriding `ToString()`, you have control over how the object is converted to a
string.
v Example:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public override string ToString()
{
return $"Person: {Name}, Age:
{Age}";
}
}
Person person = new Person { Name =
"John", Age = 25 };
string str = person.ToString(); // "Person: John, Age: 25"
In summary, `Convert.ToString()` is a static method
that can be used to convert various types to a string, including handling
`null` values by returning an empty string. On the other hand, `ToString()` is
a method defined in the `Object` class, overridden by derived types to provide a
custom string representation. However, calling `ToString()` on a `null` object
will result in a `NullReferenceException`. The choice between
`Convert.ToString()` and `ToString()` depends on the context, whether you need
to handle `null` values and whether you want to provide a custom string
representation for a specific type.
0 Comments