Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the string type have a .ToString() method?

Tags:

string

c#

Why does the string data type have a .ToString() method?

like image 283
CJ7 Avatar asked May 06 '10 06:05

CJ7


People also ask

Why does string have a toString method?

The java toString() method is used when we need a string representation of an object. It is defined in Object class. This method can be overridden to customize the String representation of the Object .

Does string have a toString method?

String toString() is the built-in method of java. lang which return itself a string. So here no actual conversion is performed. Since toString() method simply returns the current string without any changes, there is no need to call the string explicitly, it is usually called implicitly.

What is the purpose of the toString () method in object Why is it useful?

toString() method returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read.

What is the purpose of the toString () method inside a class definition?

The toString() method This method is used to transform an object into a String. Typically, it is used to construct a string containing the information on an object that can be printed, and we can redefine it for a certain class.


1 Answers

The type System.String, like almost all types in .NET, derives from System.Object. Object has a ToString() method and so String inherits this method. It is a virtual method and String overrides it to return a reference to itself rather than using the default implementation which is to return the name of the type.

From Reflector, this is the implementation of ToString in Object:

public virtual string ToString() {     return this.GetType().ToString(); } 

And this is the override in String:

public override string ToString() {     return this; } 
like image 172
Mark Byers Avatar answered Oct 09 '22 09:10

Mark Byers