2

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()
Community
  • 1
  • 1
Nalaka526
  • 11,278
  • 21
  • 82
  • 116

5 Answers5

8

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.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
6

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.

RichieHindle
  • 272,464
  • 47
  • 358
  • 399
2

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.

Joey
  • 344,408
  • 85
  • 689
  • 683
1

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.

spender
  • 117,338
  • 33
  • 229
  • 351
1

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.

JB.
  • 1,103
  • 1
  • 20
  • 37