this == null ?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

while investigating the Framework dlls via Reflector, I found this code :

System.Drawing.Graphics :
public void DrawImage(Image image, int x, int y)
{
if (this == null)
throw new ArgumentNullException("this");

...
}

I was thinking of a mistake because from an OO aspect of view, I cannot
consider "this" to be ever null. It's inconceivable to call an instance
method of an instance that does not exist !

But I have just found another case :

System.AppDomain :
public ObjectHandle CreateInstance(string assemblyName, string typeName)
{
if (this == null)
throw new NullReferenceException();

...
}



So, am I miss something ?
 
Hmmm interesting.
A couple of thoughts...
1. Well it's possible to call a method on a null instance of a type which
cannot be detected until runtime. This would cause an Exception *but* I
don't think execution would get as far as the comparison because this method
is only accessible through the type anyhows.
2. Possibly the more likely scenario is that this relates to Garbage
Collection. Obviously an objects methods are still available even after you
have called it's Dispose() method. Maybe the instance equates to null once
it's been added to the GC stack.

The comparison does however seem like a contridiction of terms :)

Be very interested to get the lowdown on this.
 
I was thinking of a mistake because from an OO aspect of view, I cannot
consider "this" to be ever null. It's inconceivable to call an instance
method of an instance that does not exist !

Well early beta versions of C# allowed you to do just that, and I
guess it's still possible in IL assembler. I wouldn't bother checking
for it though, since the code likely will fail with a
NullReferenceException eventually anyway.



Mattias
 
Hi,


Well it may also be a plain and simple human error, an overseazlos
programmer :)

cheers,
 
Mattias Sj?gren said:
Well early beta versions of C# allowed you to do just that, and I
guess it's still possible in IL assembler. I wouldn't bother checking
for it though, since the code likely will fail with a
NullReferenceException eventually anyway.

It reminds me a bit of how Delphi works. In Delphi you can check Self (This) against null on
instance calls. Its not really useful, but often useful during debugging to set a watch on Self.


--
Chad Z. Hower (a.k.a. Kudzu) - http://www.hower.org/Kudzu/
"Programming is an art form that fights back"

Get your ASP.NET in gear with IntraWeb!
http://www.atozed.com/IntraWeb/
 
Back
Top