From: Jehu Galeahsa on
On May 10, 9:52 pm, Tom Shelton <tom_shel...(a)comcast.invalid> wrote:
> It happens that Jehu Galeahsa formulated :
>
> > Hello:
>
> > What is the correct/typical way to handle null "this" arguments passed
> > to an extension method?
>
> > Thanks,
> > Travis Parks
>
> Well, for consistancy, I generally throw a null reference exception -
> just like any other instance method would do if called on a jull
> reference exception.
>
> --
> Tom Shelton

I might ask... what would Microsoft do?
From: Peter Duniho on
Jehu Galeahsa wrote:
> I might ask... what would Microsoft do?

You don't have to ask. You can look yourself. And they do it both
ways. I can't speak for Microsoft, but looking at the examples in
System.Linq.Enumerable, I would say that in general, if the
NullReferenceException would occur right away, they don't bother
validating the argument.

It looks like the main reason they validate the argument and throw a
specific exception is if the exception would otherwise be delayed,
especially after the extension method has created a new object, or even
after the extension method returns. For example, methods like Concat()
and Cast() simply copy the passed-in reference to a new object that's
returned by the method. An exception wouldn't occur until the caller
actually tries to use that object.

So, I stand by my previous suggestion: in general, a null "this"
argument should result in a NullReferenceException
(System.Linq.Enumerable uses ArgumentNullException when they check
explicitly�of course a NullReferenceException is thrown when they
don't). If the extension method dereferences the "this" argument
immediately, then no explicit check would be needed. But if you're
storing the argument somewhere and it may be dereferenced later, you
should do an explicit check and throw if it's null.

Pete
First  |  Prev  | 
Pages: 1 2
Prev: Interface as a field
Next: Newsgroup Server Software