Extension & ldquo; Object & rdquo; With null control more readable than...
source link: https://www.codesd.com/item/extension-object-with-null-control-more-readable-than-referenceequals.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Extension & ldquo; Object & rdquo; With null control more readable than ReferenceEquals
I tried to extend "object" to allow a more readable check if an object is null.
Now, object.ReferenceEquals
really checks for a null object, (the rare times it will not apply are since the operator ==
can be overridden. the object.Equals(null)
method can also be overridden).
But the object.ReferenceEquals(null, obj);
is not too readable is it?... So, I thought, why not write an extension method to the System.object
that will provide that check using object.IsNull(obj);
I've tried:
public static class MyExtClass
{
// the "IsNull" extension to "object"
public static bool IsNull(this object obj)
{
return object.ReferenceEquals(obj, null);
}
}
public SomeOtherClass
{
public static void TryUsingTheExtension()
{
object obj;
// Why does this line fail? the extension method is not recognized
// I get: 'object' does not contain a definition for "IsNull"
bool itIsANull = object.IsNull(obj);
}
}
What did I miss?
bool itIsANull = obj.IsNull();
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK