user7128918
user7128918

Reputation:

Update automatically property

I have one class :

public class Car
{
     public string Color { get; set; }

        public string Speed { get; set; }

        public string Property3 { get; set; }
}

I want to set automatically the value of Property3 when property Color or Speed are updated

I want to set the value of Property3 with the concatenation of value Color and Speed separated with hyphen

What is the best way to do this ?

Upvotes: 1

Views: 40

Answers (3)

Zoel Pancawardana
Zoel Pancawardana

Reputation: 33

you can set that getter property like this

public string Property3 { 
   get { return Color + "-" + Speed; }
}

Upvotes: 1

fixagon
fixagon

Reputation: 5566

You have two ways:

Update the dependent property within setters of speed and color:

private string _Color;
public string Color
{
    get
    {
        return this._Color;
    }
    set
    {
        this._Color = value;
        this.Property3 = $"{this.Color}-{this.Speed}";
    }
}

private string _Speed;
public string Speed
{
    get
    {
        return this._Speed;
    }
    set
    {
        this._Speed = value;
        this.Property3 = $"{this.Color}-{this.Speed}";
    }
}
public string Property3 { get; set; }

Concatenation within get of the dependent property:

public string Property3
{
    get
    {
        return $"{this.Color}-{this.Speed}";
    }
}

Conceptual difference is quite obvious: Do you want to be able to overwrite Property3 or should it be read only.

Upvotes: 0

KMoussa
KMoussa

Reputation: 1578

You can specify that in the getter of Property3 - something like this:

public string Property3 
{
    get { return $"{this.Color}-{this.Speed}"; }
}

I assume that you want Property3 to be read only so I omitted the setter in the sample above

Upvotes: 2

Related Questions