What is the usage of tostring in c#?
In C#, the ToString() method is a method of the Object class, used to convert the value of an object into a string representation. This method can be called by all C# objects, as all C# classes inherit from the Object class.
The main purpose of the ToString() method is to easily convert an object to a string for display or output. By default, ToString() returns the fully qualified name of the object. However, it can be overridden to return a custom string representation of the specific object.
Here is an example of how to use the ToString() method:
- Utilize the default ToString() method.
int number = 10;
string numberString = number.ToString();
Console.WriteLine(numberString); // 输出:"10"
- Rewrite the ToString() method.
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public override string ToString()
{
return $"Person: {Name}, Age: {Age}";
}
}
Person person = new Person { Name = "John", Age = 25 };
string personString = person.ToString();
Console.WriteLine(personString); // 输出:"Person: John, Age: 25"
- 手动调用ToString()方法:
DateTime currentDate = DateTime.Now;
string dateString = currentDate.ToString("yyyy-MM-dd");
Console.WriteLine(dateString); // 输出当前日期的字符串表示形式,例如:"2021-01-01"
In conclusion, the ToString() method is a common method used to convert an object into a string, which is very useful when you need to display the value of an object as a string.