简体   繁体   中英

Replacing the .ToString() Method C#

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

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());
  }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM