Alex Rivera | Logout

Method call if not null in C#

Asked 2009-05-16T12:15:04.997
146

Is it possible to somehow shorten this statement?

if (obj != null)
    obj.SomeMethod();

because I happen to write this a lot and it gets pretty annoying. The only thing I can think of is to implement Null Object pattern, but that's not what I can do every time and it's certainly not a solution to shorten syntax.

And similar problem with events, where

public event Func<string> MyEvent;

and then invoke

if (MyEvent != null)
    MyEvent.Invoke();
Edit
Report

1 Answer

1

Maybe not better but in my opinion more readable is to create an extension method

public static bool IsNull(this object obj) {
 return obj == null;
}
answered 2009-05-16T12:18:30.840

Your Answer