Possible Duplicates:
Safe Navigation Operator in C#?
Shortcut for “null if object is null, or object.member if object is not null”
in my XML processing project, i have to navigate through chained property to get the desired value. e.g, obj1.obj2.obj3.obj4.obj....Value
. and it is quit possible that any of the object in this chain is null.
I googled for "NullSafe Navigation in c#" and found some nice articles. From one of the Post, I got an idea to implement Custom Extension. Now I have a question regarding the performance about this extension. I have these 3 solution. can anyone suggest me which one is the best to adopt (in terms of performance)?
Option1 (using logic explained on this article):
//custom extension method public static TOutput IfNotNull<TInput, TOutput>(this TInput x, Func<TInput, TOutput> f) where TInput : class where TOutput : class { return x == null ? null : f(x); } //with custom extension method -- Very neat & clean.. but what about performance? string x = obj1 .IfNotNull(x => x.obj2) .IfNotNull(x => x.obj3) .IfNotNull(x => x.obj4) .IfNotNull(x => x.obj5) .IfNotNull(x => x.Value);
Option2:
//with NullCheck -- probably right way? if(obj1 != null && obj1.obj2 != null && obj1.obj2.obj3 != null && obj1.obj2.obj3.obj4 != null && obj1.obj2.obj3.obj4.obj5 != null) { string x = obj1.obj2.obj3.obnj4.obj5.Value; }
Option3:
//with try-catch.. With lowest cyclomatic complexity, but not a right approach. try { string x = obj1.obj2.obj3.obnj4.obj5.Value; } catch(NullReferenceException ne) { //ignore exception }