0

I want to read in the id but I don't want it to be set once it's read in. The _processing variable is set while reading in the file and deserializing so it can be set. Is there a built-in more elegant way of handling this?

    private string _id;
    [JsonProperty(PropertyName = "id")]
    public string id
    {
        get { return _id; }
        set
        {
            if (_processing) // Only allow when reading the file
            {
                _id = value;
            }
        }
    }
Ryan Detzel
  • 5,519
  • 9
  • 37
  • 49

3 Answers3

2

If you can use init only properties (since C#9.0) (https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/init):

[JsonProperty(PropertyName = "id")]
public string Id { get; init; }

If not...

private string _id;
[JsonProperty(PropertyName = "id")]
public string Id
{
    get { return _id; }
    set { _id ??= value; } // could also throw if _id is not null
}

Unrelated but helpful link on setting default property values if they are not found in the json: Default value for missing properties with JSON.net

jjxtra
  • 20,415
  • 16
  • 100
  • 140
  • The non-init setter solution does however give the illusion to the caller that the ID can be set to another value. You can set it a second time, but nothing will happen. To prevent this you can also throw an InvalidOperationException. – Cédric Moers Dec 31 '20 at 12:42
  • Sure. It’s up to the implementor to decide – jjxtra Dec 31 '20 at 14:08
1

In C# 7.3 and earlier you can use the null-coalescing operator like so:

    set
    {
        _id = _id ?? value;
    }

In C# 8.0 and later you can do:

    set
    {
        _id ??= value;
    }

??= operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null.

Ryan Wilson
  • 10,223
  • 2
  • 21
  • 40
  • This does however give the illusion to the caller that the ID can be set to another value. You can set it a second time, but nothing will happen. To prevent this you can also throw an InvalidOperationException. – Cédric Moers Dec 31 '20 at 12:42
1

I think just using a private setter would work. Just don't call it again. You can also leave out the property name if these are the same.

    private string _id;
    [JsonProperty(PropertyName = "id")]
    public string id
    {
        get { return _id; }
        private set
        {
            _id = value;
        }
    }

or

    [JsonProperty]
    public string id { get; private set; }
Cédric Moers
  • 395
  • 1
  • 10