Click here to Skip to main content
15,896,201 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
What is the difference between:
string myString = value.toString();
And
string myString = (string)value;

Can you also provide examples please if different.
Posted

1 solution

Totally different!
When you use ToString
C#
string myString = value.toString(); 
You are calling a method in the highest derived class in the values hierarchy which implements ToString, and that method returns a string representation of the value - and every class in .NET implements Tostring, even if only via the Object.ToString implementation which returns a string containing the name of the class.

So it value is an int, containing 666:
C#
string myString = value.toString();
will give you a string "666".
If value is a DataGridView, then you will get a string containing "System.Windows.Forms.DataGridView" because DataGridView does not implement TopString itself, and relies on the default Object.ToString method.

Casting is a different process: it tries to return a value that is the type that you are casting to. It the two types are not compatible, then you will get a compilation error "Cannot convert type 'abc' to 'string'" or a run time exception "Unable to cast object of type 'abc' to type 'System.String'." if it code will compile. Casting does not change the value, it just returns it as an instance of a different class.
For example:
C#
int i = 666;
string s = (string)i;
Will give you a compiler error because you can't treat an integer as a string, and
C#
int i = 666;
object o = i;
string s = (string)o;
Won;t give you a compilation error, because you can convert some objects to a string, but will give you a run time error because you still can't treat an integer as a string!

Also have a look at the is and as keywords - they let you test values to see is a cast would work.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900