Is there a better way to avoid NullRefenrenceException other than try/catch
i.e
x => x.Child.GChild.GChildProp1
If Child Or GChild happen to be null obviously this would raise NullRefenrenceException
other solution that popped into the head, is to evaluate each expression part individually from left ?
which would be better or it there a better solution ?
Well, you could convert that into an expression tree instead of into a delegate, and carefully navigate it. But no, C# doesn’t have anything like a “null-safe dereferencing operator”. I gather the C# team has looked into it, and found it hard to come up with something which actually works the way you’d naturally want it to. That’s not to say they won’t have another look at a later date, of course 🙂
(It certainly sounds like a relatively easy language feature to implement… but I trust the team when they say there are hidden complexities!)
I wouldn’t really want to catch a
NullReferenceExceptionas a way round this though… I’d prefer to write a method which checked for null references explicitly for the particular case. It depends on your situation though.