0

currently we have the code as

var val = (returnCode as Code).Element(1).Attribute[2].Value

you can see, the code get the return value, which is a fixed Object, it is very dangerous, could be null reference exception

we could write a lot of if to do the null check, but is there any other gracefully way to handle that ?

allencharp
  • 1,101
  • 3
  • 14
  • 31
  • 1
    Are you looking for `?.` – Dmitry Bychenko Sep 04 '17 at 14:05
  • Have a look at [null conditional operator](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators) – Daniel B Sep 04 '17 at 14:06
  • Don't know if that's intended, but remember that 'returnCode' can also be null in your code. – Maciej Jureczko Sep 04 '17 at 14:08
  • I never understand why people use (variable as Type).someProperty. If you using `as` keyword you probably expect that object might be of some different type and you get null in that case. If not then do direct cast is better option. IMHO. Sorry for off topic. – Renatas M. Sep 04 '17 at 14:22
  • 1
    @Reniuz `as` used to be quite a bit faster than direct casts, so optimisation is one reason though the differences are not as strong as they used to be. In this case it's also possible that that possible null is one they want to include along with the others (not clear in wording of question). If you do handle the null that is definitely better than using both `is` and direct cast. (Also though, now in C# 7 we can do both `is` and `as` at the same time). – Jon Hanna Sep 04 '17 at 14:48

1 Answers1

0

If you are afraid of potential null during the evaluation of the expression, use the elvis operator ?. instead of . to securely access properties :

// val will be null if any in the chain is null
var val = (returnCode as Code)?.Element(1)?.Attribute[2]?.Value; 

You can also use the ?[ to check array is not null before access an index :

Attribute?[2]
Pac0
  • 21,465
  • 8
  • 65
  • 74
  • First piece of code is useless and the second one will work only with C# 6+ – mrogal.ski Sep 04 '17 at 14:12
  • @m.rogalski Ok for the first part, I misread the question it seems. For the second part i don't see where there is any requirement of outdated C# version in the question. – Pac0 Sep 04 '17 at 14:15
  • Your example will throw exception even if the last property is null. That's not the what null check is about. – mrogal.ski Sep 04 '17 at 14:18
  • Yes, thank you. I edited my initial comment, and my answer. – Pac0 Sep 04 '17 at 14:19