Jelle Druyts .NET Consultant
Just another ignorant weirdo from Antwerp, Belgium trying to make sense out of it all
I'm currently having fun at a client migrating the custom .NET framework I've helped build 3,5 years ago to the wonderful world of .NET 2.0. One of the more confronting things about it is that I stumble across pieces of code that I'm not really proud of or would do totally different today.
I'll spare you the details, but I think the following code snippet that I just came across says enough:
Public Class DataSetHelper Private m_Data As DataSet Public Sub New(ByVal data As DataSet) If data Is Nothing Then Throw New NullReferenceException("Class cannot be instantiated with its DataSet set to null.") End If m_Data = data End Sub ' Snip... End Class
That just feels like throwing an OutOfMemoryException yourself... In my defense: at least I was doing argument checking
OutOfMemoryException
Time sure has flown since I was thrown into .NET 1.0... What's your favorite junior mistake?
Update: as a co-worker correctly pointed out, I should probably elaborate a bit on why this is a mistake...
Throwing a NullReferenceException is something that you should never do yourself. Just like throwing that OutOfMemoryException. It's a task that is reserved for the CLR when it finds that some code is invoking a method on a reference that has no object instance (a.k.a. it's null). To quote the MSDN documentation on NullReferenceException: "The exception that is thrown when there is an attempt to dereference a null object reference. Note that applications throw the ArgumentNullException exception rather than the NullReferenceException exception discussed here."
NullReferenceException
null
So if you want to validate that arguments which have been passed into a method, are null but shouldn't be, then you should simply throw an ArgumentNullException with just the parameter name and nothing more:
ArgumentNullException
If data Is Nothing Then Throw New ArgumentNullException("data") End If
For more fun with NullReferenceExceptions, don't miss my winning contest entry on Brad Abrams' pop quiz.
NullReferenceExceptions