简体   繁体   中英

To override ToString() method with properties or fields?

  • When should I override the ToString() method with class properties and when with fields?
  • Is there only one way valid or both are?
  • If both are ok, in which cases should we use each of the ways?

     public override string ToString() { return String.Format("{0},{1}", this.field1, this.field2); // ..or return String.Format("{0},{1}", this.Property1, this.Property2); } 

Please help???

Either are acceptable.

However, one thing to consider is that properties are more generally accepted as "public-facing" whereas fields are typically considered "private" by most C# developers.

As a result, if you wanted to be able to call .ToString() on internal values that aren't modified directly, use fields (and keep them private). If you are fine with them being modified externally and those externally modified values being returned via .ToString() , use properties.

Finally, if you needed to do any sort of additional "logic" on the property value before returning it, a property would be preferable since you can modify it in the property's getter .

Obviously, You should override ToString method, when you want to return a string you prepared specially. It's not a reuirement.

  • Both ways are ok, although using properties is highly recommended because you will have more of a control over the return values.

Often, properties represent fields, eg

   // Property1 represent field1
   public String Property1 {
     get {
       if (null == field1)  
         return "[empty]"; // <- more readable 

       return field1;
     }
   } 

and that's why properties often are more readable and thus, IMHO, preferable; however, fields are also a good choice (especially if there's no property that wraps the field).

  // Terse C# 6.0 syntax 
  public override string ToString() {
    return $"{Property1},{Property2}";
  }

If getter contains some logic, eg it uses field's value to calculate result, then use property. As a user of your class I'd be surprised to see different values in UI (if I used property directly) and in stack trace if I used ToString().

Edited: By default classes should not provide instance fields that are public or protected. So I'd recommend you to avoid using fields in ToString() when properies are available, because you may expose some sensitive data or incorrect object's state.

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