I have an .NET Core API that has to return the following output,
{
"TotalValue":200,
"Count":100,
"TypeA":
{
"TotalValue":200,
"Count":100
}
"TypeB":
{
"TotalValue":200,
"Count":100
}
}
I've tried the following to achieve this,
public interface IValue
{
public int TotalValue { get; set; }
public int Count { get; set; }
}
public class Type : IValue
{
public int TotalValue { get; set; }
public int Count { get; set; }
}
public class Test
{
public int TotalValue
{
get
{
return TypeA?.TotalValue ?? 0 + TypeB?.TotalValue ?? 0;
}
}
public int Count
{
get
{
return TypeA?.Count ?? 0 + TypeB?.Count ?? 0;
}
}
public Type TypeA { get; set; }
public Type TypeB { get; set; }
}
But the values get not added at all, I feel like there is a lot of duplication that could be avoided in this way even if I get it to work, Is there a more elegant solution to achieve this?
I have to set the values of TypeA and TypeB separately, the value of TypeA gets set but when I set the value to TypeB, the summation is not happening.
The summation does not seem to occur due to the precedence of the operator ??
. When you write this:
TypeA?.TotalValue ?? 0 + TypeB?.TotalValue ?? 0;
It may actually mean this:
(TypeA?.TotalValue) ?? (0 + TypeB?.TotalValue ?? 0);
So if you have TypeA
not null, only its TotalValue
returned. The value from TypeB
is ignored no matter it's null or not. If you have TypeA
null and TypeB
not null. The returned value then is from TypeB.TotalValue
.
In case you're not sure about the operator's precedence, you should explicitly use parentheses to group the expressions the way you want. It also helps make the expression clearer.
To fix it, just group the way you want (as I understand) like this:
public int TotalValue
{
get
{
return (TypeA?.TotalValue ?? 0) + (TypeB?.TotalValue ?? 0);
}
}
public int Count
{
get
{
return (TypeA?.Count ?? 0) + (TypeB?.Count ?? 0);
}
}