Brief introduction to the use of overriding ToString methods in C classes or structures

  • 2021-09-05 00:41:29
  • OfStack


Every class or structure in C # implicitly inherits the Object class. Therefore, every object in C # gets the ToString method, which returns a string representation of the object. For example, all variables of type int have an ToString method that causes the variables to return their contents as strings:


int x = 42;
string strx = x.ToString();
Console.WriteLine(strx);

Output:


42

When you create a custom class or structure, you should override the ToString method to provide type information to client code.

When you decide the type of information provided through this method, consider whether your class or structure will be used by untrusted code. Make sure you don't provide any information that could be exploited by malicious code.
Overriding an ToString method in a class or structure
The ToString method is declared with the following modifiers and return types:


public override string ToString(){}

Implement this method so that it returns 1 string.
The following example returns the name of the class and data specific to an instance of the class.


class Person
{
  public string Name { get; set; }
  public int Age { get; set; }

  public override string ToString()
  {
    return "Person: " + Name + " " + Age;
  }
}

You can test the ToString method, as shown in the following code example:


Person person = new Person { Name = "John", Age = 12 };
Console.WriteLine(person);

Output:


Person: John 12


Related articles: