c# - Adding Count of Arrays Together returns 0 -
i have following class, arrays populated
public class internaltag_relatedobjectsviewmodel { public guid[] branchids { get; set; } public guid[] companyids { get; set; } public guid[] contactids { get; set; } public guid[] divisionids { get; set; } public guid[] tenderids { get; set; } public guid[] projectids { get; set; } public guid[] documentids { get; set; } public guid[] newsids { get; set; } public guid[] photosids { get; set; } public int total { { return (this.branchids?.count() ?? 0 + this.companyids?.count() ?? 0 + this.contactids?.count() ?? 0 + this.divisionids?.count() ?? 0 + this.tenderids?.count() ?? 0 + this.projectids?.count() ?? 0 + this.documentids?.count() ?? 0 + this.newsids?.count() ?? 0 + this.photosids?.count() ?? 0); } } }
the class populated , returned following method, on class
static void main(string[] args) { internaltag_relatedobjectsviewmodel test = new internaltag_relatedobjectsviewmodel() { companyids = new guid[] { guid.newguid() }, newsids = new guid[] { guid.newguid(), guid.newguid() } }; console.write(test.total); }
but total returns 0, when of arrays have data. missing something?
you're missing precedence, basically.
it's easier see what's going on when reduced minimal example:
using system; public class program { public static void main() { string[] = { "x", "y" }; string[] b = { "x" }; int first = a?.length ?? 0 + b?.length ?? 0; int second = (a?.length ?? 0) + (b?.length ?? 0); console.writeline(first); // prints 2 console.writeline(second); // prints 3 } }
obviously 3 right answer here. what's going on?
the ??
operator has lower precedence +
, first
here equivalent to:
int first = ((a?.length ?? (0 + b?.length)) ?? 0;
to split up:
int? step1 = a?.length; // 2 int? step2 = step1 ?? (0 + b?.length); // 2 int first = step2 ?? 0;
note how because result of step1 non-null, never end taking length of b
.
you want apply ??
operator on result of each nullable length expression, brackets around (a?.length ?? 0)
want.
Comments
Post a Comment