Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a IsNull() method

Tags:

c#

isnull

I'm trying to make a method similar to .ToString() that checks whether the object is null or not. I just done know how to make it accessible without calling the class

public class ObjectExtensions
{
    public static bool IsNull(object obj)
    {
        bool val = false;
        if (obj == null)
        { val = true; }
        return val;
    }
}
like image 528
Liaoo Avatar asked Mar 30 '26 15:03

Liaoo


2 Answers

You're missing the this modifier to make it a true extension method as well as making the object static.

public static class ObjectExtensions
{
    public static bool IsNull(this object obj)
    {
        return obj == null;
    }
}

Then you can call it like so:

var fooIsNull = foo.IsNull();
// which is syntactic sugar for
fooIsNull = ObjectExtensions.IsNull(foo);
like image 129
JG in SD Avatar answered Apr 02 '26 04:04

JG in SD


Your class needs to be static and you need the "this" keyword before the extended variable type:

public static class ObjectExtensions
{
    public static bool IsNull(this object obj)
    {
        bool val = false;
        if (obj == null)
        { val = true; }
        return val;
    }
}

Also, as you are doing a single boolean check, you can return it's results directly:

public static class ObjectExtensions
{
    public static bool IsNull(this object obj)
    {
        return obj == null;
    }
}

Here a link to MSDN entry for Extension Methods

like image 35
lstern Avatar answered Apr 02 '26 03:04

lstern



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!