What is difference between Convert.tostring and .tostring() method ?

Most of developers know how to use these methods to convert a type to string, but when it comes to differentiate  these methods  they usually can't express the answer.

Today we will learn the main difference between these two.

In most of articles you will find a common answer that Convert.tostring handles NULL where  .tostring() can't.

Then the question is that  why .tostring() has been implemented  when Convert.ToString() is doing all the jobs effectively.

Convert.tostring() method convert a type to String type (type conversion occures) where .ToString() represent a type to string type if a type not able to represent in string then it will throw exception.(no type conversion occurs).
1
2
3
4
5
6
7
8
9
10
11
<span class="line-number"><span><a>1</a></span><span><a>2</a></span><span><a>3</a></span><span><a>4</a></span><span><a>5</a></span><span><a>6</a></span><span><a>7</a></span><span><a>8</a></span><span><a>9</a></span><span><a>10</a></span><span><a>11</a></span></span>// Comment
//Returns a null reference exception
string mystring;
string str = null;
mystring= str.ToString();
 
//Returns an empty string for str and does not throw an exception.
string str;
string s= null;
str = Convert.ToString(s);
<span class="cl"></span>
Actually .ToString()  is used to  represent  a  object into string representation by overridding .ToString() method. Here is the example-


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
using System;
class Example
{
    int _a;
    int _b;
 
    public Example(int a, int b)
    {
 _a = a;
 _b = b;
    }
 
    public override string ToString()
    {
     return string.Format("[{0}, {1}]", _a, _b);
    }
}
 
class Program
{
    static void Main()
    {
 Example obj = new Example(10, 20);
 Console.WriteLine(obj);
    }
}
Output
 
[10, 20]
In above example line Console.WriteLine(obj) is writing a object which is not acceptable,but as we are overriding the .ToString() method it will format that object into string representation as written in line string.Format("[{0}, {1}]", _a, _b);

Hope you like the tutorials.

Thanks. 


What is difference between Convert.tostring and .tostring() method ? What is difference between Convert.tostring and .tostring() method ? Reviewed by CodiBucket on 08:54 Rating: 5

No comments:

Powered by Blogger.