user2994834
user2994834

Reputation: 395

re updating of "Key" value is not reflecting with "ForEach"

I have a below class where I am setting "Key" value,

public class DataCls
{
    private string _key;

    public string Message { get; set; }
    public string Priority { get; set; }
    public string Key
    {
        get
        {
            return _key = $"{Message}:{Priority}";
        }
        set
        {
            _key = value;
        }
    }
}

Now, the "Key" value is coming automatically while I am adding some "Message" and "Priority",

 List<DataCls> lstData = new List<DataCls>
       {
           new DataCls {Message="M1", Priority="P1" },
       };

Now. I would like update the "Key" value again with "ABC".

I tried with below "ForEach", but updated "Key" value's ("ABC") is not reflecting to the list "lstData", what I am missing?

lstData.ForEach(p => p.Key = "ABC"); 

Upvotes: 0

Views: 70

Answers (1)

Brendan Green
Brendan Green

Reputation: 11914

The issue is with your getter for Key.

Let's assume that you want to return either the Key value that was assigned by some other code, or the combination of {Message}:{Priority} otherwise.

Your current code:

public string Key
{
    get
    {
        return _key = $"{Message}:{Priority}";
    }
}

When you access Key, the string of $"{Message}:{Priority}" is assigned to _key, and then returned.

Therefore, no matter what value you set Key to, $"{Message}:{Priority}" is always returned.

If you change the get to do this instead:

public string Key
{
    get
    {
        return _key ?? $"{Message}:{Priority}";
    }
}

With this change, we use the null-coalescing operator, which will returns the left-hand operand if the operand is not null (e.g. _key); otherwise it returns the right hand operand (e.g. the string $"{Message}:{Priority}").

You will either return the value that was assigned to Key, or the string $"{Message}:{Priority}" if _key is null (i.e you haven't assigned anything to it)

Upvotes: 4

Related Questions