Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling null objects when calling methods

I have been looking around finding the best possible option for handling null objects in calling a method (or method chain).

It is our common practice to check with if condition:

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

Which can be further improved by using extension methods:

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

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

PLEASE NOTE: I normally ignore ! from my programming practice. Hence it is wise to say that for me extension methods are good to go.

However, it becomes very complicated in dealing with when the Method chain is involved.

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

How you do think it can be handled in C#, so that the CallMe is called only if customObject is not null and CallMe2 is called only if CallMe returns non null object.

Of course I can use If conditions or ternary operator. However, I would want to know if vNext, C#5.0 has some thing to offer.

like image 806
codebased Avatar asked Aug 31 '14 23:08

codebased


People also ask

Can we call method with null object?

If you call a static method on an object with a null reference, you won't get an exception and the code will run. This is admittedly very misleading when reading someone else's code, and it is best practice to always use the class name when calling a static method.

How do you handle a null check in C#?

IsNullOrEmpty() Method of C# This method is used when you want to check whether the given string is Empty or have a null value or not? If any string is not assigned any value, then it will have Null value. The symbol of assigning Null value is “ “or String. Empty(A constant for empty strings).

Can we declare object as null?

A null value is possible for a string, object, or date and time, etc. We cannot assign a null value to the primitive data types such as int, float, etc. In programming, usually we need to check whether an object or a string is null or not to perform some task on it.


1 Answers

In the upcoming C# 6 (vNext) has the ?. operator (Null Conditional Operator) which easily allow you to chain null reference checks for every nested property.

An example of this would be:

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

This was a requested feature in the Visual Studio UserVoice site

Add ?. Operator to C#

You can see the status for all the new language features for C# 6.0 on the Codeplex site for Roslyn:

C# 6 Language Features Status

like image 98
Scott Wylie Avatar answered Sep 17 '22 18:09

Scott Wylie