Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting to string versus calling ToString

Tags:

c#

object obj = "Hello";
string str1 = (string)obj;
string str2 = obj.ToString();

What is the difference between (string)obj and obj.ToString()?

like image 225
Embedd_0913 Avatar asked Oct 14 '09 09:10

Embedd_0913


People also ask

What happens if you call ToString on a string?

ToString is a method defined in the Object class, which is then inherited in every class in the entire framework. The ToString method in the String class has been overwritten with an implementation that simply returns itself. So there is no overhead in calling ToString() on a String-object.

Why do we use ToString in C#?

Object. ToString is the major formatting method in the . NET Framework. It converts an object to its string representation so that it is suitable for display.

What is the difference between string and ToString?

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.

What is the difference between ToString and Asstring in Java?

In Java, toString creates a new string fully disconnected from the object (and there's no other way because of immutability). The same holds e.g., for Collection#toArray , while Arrays#asList returns a view of the array, which is bidirectionally connected (mutating the array changes the list and vice versa).


2 Answers

  • (string)obj casts obj into a string. obj must already be a string for this to succeed.
  • obj.ToString() gets a string representation of obj by calling the ToString() method. Which is obj itself when obj is a string. This (should) never throw(s) an exception (unless obj happens to be null, obviously).

So in your specific case, both are equivalent.

Note that string is a reference type (as opposed to a value type). As such, it inherits from object and no boxing ever occurs.

like image 177
Mac Avatar answered Oct 24 '22 00:10

Mac


If its any help, you could use the 'as' operator which is similar to the cast but returns null instead of an exception on any conversion failure.

string str3 = obj as string;
like image 18
Nick Masao Avatar answered Oct 23 '22 22:10

Nick Masao