Home > Software design >  c# , how to not repeat a long chain of method calls to check whether an object is null or not before
c# , how to not repeat a long chain of method calls to check whether an object is null or not before

Time:07-27

for example,

if(method1().method2().method3().method4().method5().object != null)
{
 var value =  method1().method2().method3().method4().method5().object;
} 

I have came across and written many such scenarios in c#, (ex:- while working with selenium frameworks) where a specific object can only be access through a long chain of method callings, and having to check for null before accessing objects value to not get exceptions. Feels like above code is bit too redundant. What coding pattern is/are used to make above code better? How to not write method calling chain 2 times ?

CodePudding user response:

Even before C# 7, you could just use a local variable:

var something = method1().method2().method3().method4().method5().object;
if (something != null)
{
    // Use something
}

In C# 7 you can also use a pattern:

if (method1().method2().method3().method4().method5().object is object value)
{
    // Use value
}

Note that you can't use var for this; the var pattern matches against a null, whereas you want to only match if it's non-null. Just use the appropriate type. (We can't tell what it is from the question...)

CodePudding user response:

You can use the null conditional operator with a local variable. That would save the 2nd call and also checking the null at each method return. You can read about null conditional operator at here.

var result = method1()?.method2()?.method3()?.method4()?.method5()?.object;
if(result != null)
{
    var value =  result ;
}  
  •  Tags:  
  • c#
  • Related