Possible Duplicate:
C#: why does the string type have a .ToString() method
Why is there a ToString
method exist in String
class (VB.NET)?
String.ToString()
Will it be a overhead if it is used like
TextBox.Text.ToString()
Possible Duplicate:
C#: why does the string type have a .ToString() method
Why is there a ToString
method exist in String
class (VB.NET)?
String.ToString()
Will it be a overhead if it is used like
TextBox.Text.ToString()
The ToString
method is found on Object
from which String
inherits. The implementation of Object.ToString
is to print the typename.
public virtual string ToString() {
return this.GetType().ToString();
}
The type String
overrides this method to return itself.
public override string ToString() {
return this;
}
The code TextBox.Text.ToString()
has an unnecessary call to ToString
, but it is unlikely that there will be any noticable performance impact from doing so.
All objects have ToString()
, so that for any object:
you can call obj.ToString()
without knowing the type of obj
you can call obj.ToString()
without having to worry about the method not being there (generic logging code is a common example of where you might do this)
The overhead of calling ToString()
on a string is only a call to a one-line function, so it's almost certain to be negligible.
ToString()
exists in every class derived from System.Object
. And yes, that includes System.String
as well.
It's perhaps a bit superfluous there and the documentation states that it will return the exact same instance. So there is no performance overhead there except for the method call.
Everything is an object (or can be boxed as an object). object
defines the method ToString
, ergo, string has a ToString method, because it's an object.
Because the System.String
class, like any other class is derived from the System.Object
class,
it automatically inherits from various methods like :
public virtual bool Equals(Object obj)
public virtual int GetHashCode()
public virtual string ToString()
thus enabling you to compare, fill tables with objects, and turn objets into human-friendly strings.