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;
}
}
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With