Home > Blockchain >  Replacing the .ToString() Method C#
Replacing the .ToString() Method C#

Time:01-02

When i make a new class, and Write it to the Console, it returns me the ToString() Function by default, is there like a way to override what function it returns?

For Example if id want to Return a Boolean as a default Value

So I'd do Console.WriteLine(ExampleClass);

and it should return true or false, instead of a String

CodePudding user response:

Converting an object to a string will always implicitly call the ToString method, you cannot choose a different method.

Implement your ToString method to return "true" or "false":

class YourClass {
  public override string ToString() {
    return "true"; // or return "false"; depending on your needs.
  }
}

You can call another method explicitly though:

class YourClass {
  public string MyToString() {
    return "true"; // or return "false"; depending on your needs.
  }

  public static void Main() {
    Console.WriteLine(new YourClass().MyToString());
  }
}

CodePudding user response:

You can use DebuggerDisplay which overwrites the default ToString() method in case of debugging. See more details on msdn.

For runtime you need an implizit ToString() overload / override, like already wrote as answer.

  •  Tags:  
  • c#
  • Related