what is the point of allowing invocation of extension methods on null objects? this is making me unnecessarily check for a null object in the extension method. AFAIK,i can't understand this? Please explain.
Extension methods are syntactic sugar of the C# language, they get compiled to normal static method calls in ILCode. A static method doesn't know anything about the parameters at compile time.
Simply put, why not?
You can sometimes skip the test if the first method you call within the extension would also throw the correct error.
You're essentially asking for the code to be different so that:
This seems a lot of an imposition on other uses just to save the one line of:
if(arg == null)throw new ArgumentNullException();
Extension methods are just syntactic sugar. In reality they are static methods on another class, so since you can write
IEnumerable<int> foo = null;
Enumerable.Count(foo);
You can also write
IEnumerable<int> foo = null;
foo.Count();
Sometimes, allowing the extension method to be called on a null object simplifies your code by allowing you to move the null check into the method instead at the call site. For example, you may have an extension method that returns a List<T>
, but if called on a null object, returns an empty List<T>
.
Another beautiful example that wouldn't be possible otherwise:
public static bool IsNullOrEmpty(this string value)
{
return string.IsNullOrEmpty(value);
}
So you can use
string s = null;
if (s.IsNullOrEmpty()) // no null reference error!
...
Instead of
string s = null;
if (string.IsNullOrEmpty(s))
....
NullArgumentException
could take execution time and the user may want to assert instead or use something else. Extension methods are just static methods:
List<int> x = null;
x.Count()
Is equivalent to:
List<int> x = null;
System.Linq.EnumerableExtensions.Count(x);
//EnumerableExtensions may not be the class, but you get the idea
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.