0

i have

List<someobjects> listOfObj;

i have some property where i'd like to return number of objects i tried it like

get => (int)listOfObj?.Count();

but app crashes with System.Reflection.TargetInvocationException somewhere in xamarin.forms page initializecomponent (the above said property is binded to some control )

when i change code to

get => (listOfObj==null)?0: listOfObj.Count();

all works as expected .

i think these two versions are the same , but may be i'm missing something ?

tia ish

ish1313
  • 321
  • 3
  • 6
  • 7
    *i think these two versions are the same* you are wrong ... in first you obviously trying cast `null` to `int` **edit:** long story `listOfObj?.Count()` in fact return `Nullable` which is not null but when it doesn't has value it cannot be casted to int – Selvin Oct 03 '19 at 15:18
  • What happened when you tried them? – ProgrammingLlama Oct 03 '19 at 15:20
  • 3
    If you want an alternative, you can use `get => listOfObj?.Count() ?? 0;` – itsme86 Oct 03 '19 at 15:21
  • No, it's not the equivalent. The equivavelent would be: `listOfObj?.Count() ?? 0` === `(listOfObj==null) ? 0 : listOfObj.Count()` – Sergey Shevchenko Oct 03 '19 at 15:21
  • thanks, i hit post too early ;) for some reasons i thought that this cast (int) (int?) will do value == null ?? default (int). but i was wrong – ish1313 Oct 03 '19 at 15:48

0 Answers0