0

I am trying to parse a null from our api into an int like this:

API:

"thresholdMax": 10,
                    "thresholdAvg": null,
                    "thresholdMin": 40

Datamodel:

public int thresholdMax { get; set; }
        public int thresholdAvg
        { 
            get { return thresholdAvg; }
            set
            {
                try
                {
                    thresholdAvg = value;
                }
                catch
                {
                    thresholdAvg = 0;
                }
            }

        }
        public int thresholdMin { get; set; }

But it fails saying it cannot parse null to int. I though however that with how I am setting these values, it should work.

What is the best practice, if I dont want to convert the type to string?

innom
  • 770
  • 4
  • 19
  • Value types, such as `int`, cannot be set to null. Do you want to allow `thresholdAvg` to be null? – gunr2171 May 11 '22 at 11:41
  • A setter on an average, a max < min... there are many many questions as to what you are actually trying to accomplish. – oerkelens May 11 '22 at 11:43
  • it does. feel free to answer my posst :) – innom May 11 '22 at 11:43
  • You can use Nullable value types. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types – ihsany May 11 '22 at 11:44
  • 1
    In addition, your current try/catch is not doing what you think it should do. `thresholdAvg = value;` can't throw an exception. Remember there's a difference between a json property being `null` and a json property being excluded entirely. Also, using a property inside itself will cause a StackOverflow Exception. – gunr2171 May 11 '22 at 11:46

1 Answers1

0

if you want to allow null values you could easily do:

public int? thresholdAvg { get; set; }
Daniel
  • 9,491
  • 12
  • 50
  • 66