Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between the ToString method and casting to string?

Tags:

c#

.net

object o;

Is there any difference between o.ToString() and (string) o ?

like image 295
user496949 Avatar asked Nov 11 '10 07:11

user496949


People also ask

What is the difference between toString and string?

Both these methods are used to convert a string. But yes, there is a difference between them and the main difference is that Convert. Tostring() function handles the NULL while the . ToString() method does not and it throws a NULL reference exception.

Is toString a string method?

The toString() method of a string object returns a string representing the specified string.

What is the toString method?

A toString() is an in-built method in Java that returns the value given to it in string format. Hence, any object that this method is applied on, will then be returned as a string object.

What is difference between toString and string valueOf?

String. valueOf will transform a given object that is null to the String "null" , whereas . toString() will throw a NullPointerException . The compiler will use String.


2 Answers

If you're after safe conversion from object to string just use:

string s = Convert.ToString(o);
like image 96
Shadow Wizard Hates Omicron Avatar answered Oct 27 '22 00:10

Shadow Wizard Hates Omicron


object.ToString() will convert the object into a string. If object has null value then it will throw an exception because no null value has ToString() method.

Whereas (string)object is a unboxing process of reference type to value type. Here an object value is copying into new instance of string type. If that object is null, it will assign null value.

like image 30
Sukhjeevan Avatar answered Oct 27 '22 01:10

Sukhjeevan