Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension Methods - IsNull and IsNotNull, good or bad use?

I like readability.

So, I came up with an extension mothod a few minutes ago for the (x =! null) type syntax, called IsNotNull. Inversly, I also created a IsNull extension method, thus

if(x == null) becomes if(x.IsNull())

and

if(x != null) becomes if(x.IsNotNull())

However, I'm worried I might be abusing extension methods. Do you think that this is bad use of Extenion methods?

like image 340
Jaimal Chohan Avatar asked Sep 29 '09 21:09

Jaimal Chohan


People also ask

Should extension methods check for NULL?

As extension methods are in reality static methods of another class, they work even if the reference is null . This can be utilized to write utility methods for various cases.

Are extension methods good?

Adding extension methods to any type is a great way to improve productivity and simplify code.

What is an advantage of using extension methods?

The main advantage of the extension method is to add new methods in the existing class without using inheritance. You can add new methods in the existing class without modifying the source code of the existing class. It can also work with sealed class.

Can you call an extension method on a null object?

The extension method will get a null parameter. Yes, an exception will be thrown if the method tries to access the object without first testing if it is null. A guy here wrote “IsNull” and “IsNotNull” extension methods that check is the reference passed null or not.


2 Answers

I don't find that incredibly useful, but this:

someString.IsNullOrBlank()    // Tests if it is empty after Trimming, too
someString.SafeTrim()         // Avoiding Exception if someString is null

because those methods actually save you from having to do multiple checks. but replacing a single check with a method call seems useless to me.

like image 132
Botz3000 Avatar answered Oct 03 '22 04:10

Botz3000


It doesn't seem any more readable and could confuse people reading the code, wondering if there's any logic they're unaware of in those methods.

I have used a PerformIfNotNull(Func method) (as well as an overload that takes an action) which I can pass a quick lambda expression to replace the whole if block, but if you're not doing anything other than checking for null it seems like it's not providing anything useful.

like image 27
Davy8 Avatar answered Oct 03 '22 03:10

Davy8