Handling Null Objects on Method Calls

I was looking for the best option for handling null objects when calling a method (or chain of methods).

Our usual practice is to check with the condition:

if ( customObject != null ) {
    customObject.callMe();
}

What can be improved with extension methods:

Program customObject = null;
if (customObject.NotNull()) {
    customObject.CallMe();
}

public static bool NotNull(this object o) {
    return o == null;
}

PLEASE PAY ATTENTION: I usually ignore! from my programming practice. Therefore, it is reasonable to say that extension methods are useful to me.

However, it becomes very difficult to work with the goals of the method.

customObject.CallMe().CallMe2() ex... 

What do you think, it can be processed in C #, so it CallMeis called only if customObjectit is not null, and it CallMe2is called only if it CallMereturns a non-zero object.

, If . , , vNext, # 5.0, - .

+4
6

# 6 (vNext) ?. (Null Conditional Operator), .

:

int? first = customers?.[0].Orders?.Count();

Visual Studio UserVoice.

?. #

# 6.0 Codeplex Roslyn:

# 6

+12

:

public static class Extensions
{
    public static R IfNotNull<T, R>(this T @this, Func<T, R> @select) where T : class
    {
        return @this.IfNotNull(@select, () => default(R));
    }

    public static R IfNotNull<T, R>(this T @this, Func<T, R> @select, Func<R> @default) where T : class
    {
        return @this != null ? @select(@this) : @default();
    }

    public static void IfNotNull<T>(this T @this, Action<T> @action) where T : class
    {
        if (@this != null)
        {
            @action(@this);
        }
    }
}

:

customObject 
    .IfNotNull(y => y.CallMe())
    .IfNotNull(y => y.CallMe2());
+3

# 5 , . :

  • Englobing try/catch catching NullReferenceException ( , , .. , ).

, , . # 6 Roslyn, , # 6.

customObject?.CallMe()?.CallMe2()?.[...] 

, ( , ). , ...

+2

# 6 ?, , Maybe monad, . , , . , , .

0

, , , , , .

, customObject, , , . , , . -, , , , catch , , , .

, , , , . , , .

, , , , , .

, . , , , , :

  • , .
  • , , , , .
  • , nulls , , - .

, , , . , . - .

catch - . - . , , , . , , , .

-2

. , null, , catch NullReferenceException . , , , , . , , - , , .

try
{
    customObject.CallMe().CallMe2()
}
catch (NullReferenceException ex)
{
   /* save enough details to determine why you got an unexpected null */
}

Do not use exception handling to perform common programming tasks, but do not overly avoid them, checking all possible unforeseen circumstances, as if rare. Determine which crashes are likely in your code (that you can do something) and include a healthy catch 'es list at the end of each block of a reasonable size.

-7
source

All Articles