Rafa
Rafa

Reputation: 15

How do I set a bool property using conditionals from other properties?

So I have these properties and I want to set another one depending on these:

    public DateTime? StartDate { get; set; }
    public DateTime? EndDate { get; set; }
    private bool _hasDateRange;

I want to set the _hasDateRange to true or false depending if StartDate and EndDate is different from null.

What I've come up with is this, but it doesn't seem to work;

public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
private bool _hasDateRange;
public bool HasRange
    {
        get => _hasDateRange;
        set
        {
            if (this.StartDate != null && this.EndDate != null)
            {
                this._hasDateRange = true;
            }
            else
            {
                this._hasDateRange = false;
            }
        }
    }

Upvotes: 0

Views: 328

Answers (2)

knittl
knittl

Reputation: 265231

You want a get-only property. Why would you want to be required to call a setter first to compute the value? The setter of any property should assign the value of the special variable value to the backing field of the property, not ignore it.

You want the return value of the property computed:

public bool HasRange
{
    get
    {
        if (this.StartDate != null && this.EndDate != null)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

The backing field (_hasDateRange) is now no longer required and can be removed.

Multiple reduction steps can be applied to the property's definition:

Step 1

public bool HasRange
{
    get
    {
        return this.StartDate != null && this.EndDate != null;
    }
}

Step 2

public bool HasRange
{
    get => this.StartDate != null && this.EndDate != null;
}

Step 3

public bool HasRange => this.StartDate != null && this.EndDate != null;

Upvotes: 4

Markus
Markus

Reputation: 22456

Instead of using a setter that has to be called in order to work, you can use a read only property with only a getter. In the code of the getter, check the values of the other properties and you are good to go:

public bool HasRange
{
    get => StartDate.HasValue && End date.HasValue;
}

Whenever the value of HasRange is requested, it is evaluated based upon the other properties so there is no chance that the values are out of sync

Upvotes: 1

Related Questions