C
C#6mo ago
fayton

easy question but i still didnt understand after searching google: what is the point of ToString?

There is such method where you write in a class “public override ToString()” with curly braces open where you return stuff, whats the point of that?
3 Replies
Angius
Angius6mo ago
It adds a custom conversion to string
MODiX
MODiX6mo ago
Angius
REPL Result: Success
record Foo(int Value, string Name)
{
public override string ToString()
{
return $"The value of this foo named {Name} is {Value}.";
}
}

var f = new Foo(69, "Bobbert");
Console.WriteLine(f); // converts to string implicitly
Console.WriteLine(f.ToString()); // and explicitly
Console.WriteLine($"Output is: '{f}'"); // works with interpolation
record Foo(int Value, string Name)
{
public override string ToString()
{
return $"The value of this foo named {Name} is {Value}.";
}
}

var f = new Foo(69, "Bobbert");
Console.WriteLine(f); // converts to string implicitly
Console.WriteLine(f.ToString()); // and explicitly
Console.WriteLine($"Output is: '{f}'"); // works with interpolation
Console Output
The value of this foo named Bobbert is 69.
The value of this foo named Bobbert is 69.
Output is: 'The value of this foo named Bobbert is 69.'
The value of this foo named Bobbert is 69.
The value of this foo named Bobbert is 69.
Output is: 'The value of this foo named Bobbert is 69.'
Compile: 556.780ms | Execution: 76.212ms | React with ❌ to remove this embed.
fayton
faytonOP6mo ago
thank u!
Want results from more Discord servers?
Add your server