drewwyatt
drewwyatt

Reputation: 6027

Is it possible to add a method call to a property that is not a class/object?

My class has a property that looks like this:

public string DueDateAsString
{
    get 
    {
        DateTime duedate = this.RigActionType.FrequencyType.GetDueDateForAction(this);
        if (this.HasBeenCompleted(duedate))
        {
            return "Completed";
        }
        else if (DateTime.Compare(DateTime.Today, duedate) > 0) // past due
        {
            return duedate.ToString() + " (past due)";
        }

        return duedate.ToString();
    }
}

I would like to extend the functionality a bit more so that this could also return something like "due in n days" but in a way that I don't have to create a separate property called VerboseDueDateAsString (or something).

Is it possible to do something like this:

someObject.DueDateAsString; // Outputs "4/1/2014"
someObject.DueDateAsString.Verbose; // Outputs "Due in x days"

Upvotes: 0

Views: 51

Answers (3)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112712

You could expose the due date as a property and create an extension method for the conversion. Place it in a static class whose namespace is visible where you need it.

public static string Verbose(this DateTime date)
{
    return String.Format("Due in {0} days", (DateTime.Now - date).Days);
}

Then apply it directly to the due date

Console.WriteLine(someObject.DueDate.Verbose());

If you replace your actual property with a similar exetension method you will get a consitent way of displaying due dates

public static string Concise(this DateTime date)
{
    // Place the logic of DueDateAsString here
}
Console.WriteLine(someObject.DueDate.Concise());

Upvotes: 3

Ry-
Ry-

Reputation: 225174

DueDateAsString doesn’t really seem like it should be a property in the first place.

struct DueDate {
    DateTime date;
    bool completed;

    public DueDate(DateTime date, bool completed) {
        this.date = date;
        this.completed = completed;
    }

    public override string ToString() {
        if (this.completed) {
            return "Completed";
        }

        if (DateTime.Compare(DateTime.Today, duedate) > 0) // past due
        {
            return duedate.ToString() + " (past due)";
        }

        return duedate.ToString();
    }

    public string ToVerboseString() {
        // Implement this
    }
}
⋮
public DueDate DueDate
{
    get 
    {
        DateTime duedate = this.RigActionType.FrequencyType.GetDueDateForAction(this);

        return new DueDate(duedate, this.HasBeenCompleted(duedate));
    }
}

You could use an extension method on DateTime, but then there’s still the matter of determining whether it’s completed or not.

Name it something other than DueDate, by the way.

Upvotes: 1

FGhilardi
FGhilardi

Reputation: 337

DueDateAsString would need to be an object that itself contains a Verbose method afaik

Upvotes: 0

Related Questions