Every object in C # inherits the tostring method. This method returns the string representation of the object. For example, all int-type variables have a tostring method, which allows these variables to return their content as a string:
IntX = 42;
StringStrx = x. tostring ();
System. Console. writeline (strx );
When creating a custom class or structure, you should override the tostring methodCodeProvides type information.
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 that you do not provide any information that will be exploited by malicious code.
Override the onstring method in the class or structure 1. Declare the tostring method through the modifier and return type below:
Public Override StringTostring (){}
2. implement this method to return a string.
The following example not only returns the class name, but also the data of an instance specific to the class. Note that it will also use the tostring method on the age variable to convert int to an output string.
ClassPerson
{
StringName;
IntAge;
Sampleobject (StringName,IntAge)
{
This. Name = Name;
This. Age = age;
}
Public Override StringTostring ()
{
StringS = age. tostring ();
Return "Person :"+ Name +""+ S;
}
}