Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "override string ToString()" method twice in a class

I have use to this method for the two properties defined in my class. The properties are

public bool HasImage { get; set; }
public DateTimeOffset? StartDate { get; set; }


public override string ToString()
{
    string value = "";
    if (StartDate.HasValue)
    {
        if (StartDate == DateTime.Today.Date)
            value = "1 Day";
        else if (StartDate < DateTime.Today.Date)
            value = "Past Due";
    }
    return value;
}

How to use this method for the HasImage property, here I cannot remove the method for StartDate property. The above the methods are called when exporting results to excel.

like image 234
GANI Avatar asked Feb 14 '23 05:02

GANI


2 Answers

The purpose of ToString is to create a string representation of the object itself. I.e. you don't get a ToString method per property. You get one method for the object.

If you want to turn individual properties into strings, you need to provide those methods yourself and call them explicitly as needed. E.g. something like StartDateAsString and HasImageAsString.

like image 164
Brian Rasmussen Avatar answered Feb 16 '23 03:02

Brian Rasmussen


An elegant/common way to solve this would be implementing the IFormattable interface (check link for a full example) like this:

public class MyClass : IFormattable
{
    public string ToString(string format, IFormatProvider formatProvider)
    {
        switch (format)
        {
            case "X": return x.ToString();
            case "Y": return y.ToString();
            // ...
        }

        return this.ToString();        
    }
}
like image 22
floele Avatar answered Feb 16 '23 02:02

floele