Does the method get called with a null value or does it give a null reference exception?
MyObject myObject = null;
myObject.MyExtensionMethod(); // <-- is this a null reference exception?
If this is the case I will never need to check my 'this' parameter for null?
As you've already discovered, since extension methods are simply glorified static methods, they will be called with
null
references passed in, without aNullReferenceException
being thrown. But, since they look like instance methods to the caller, they should also behave as such. You should then, most of the time, check thethis
parameter and throw an exception if it'snull
. It's OK not to do this if the method explicitly takes care ofnull
values and its name indicates it duly, like in the examples below:I've also written a blog post about this some time ago.
The extensionmethod is static, so if you don't to anything to the this MyObject it shouldn't be a problem, a quick test should verify it :)
Addition to the correct answer from Marc Gravell.
You could get a warning from the compiler if it is obvious that the this argument is null:
Works well at runtime, but produces the warning
"Expression will always cause a System.NullReferenceException, because the default value of string is null"
.There are few golden rules when you want in your to be readable and vertical.
In your case - DesignByContract is broken ... you are going to perform some logic on a null instance.
As others pointed out, calling an extension method on null reference causes the this argument to be null and nothing else special will happen. This gives raise to an idea to use extension methods to write guard clauses.
You may read this article for examples: How to Reduce Cyclomatic Complexity: Guard Clause Short version is this:
This is the string class extension method which can be called on null reference:
The call works fine only because runtime will successfully call the extension method on null reference. Then you can use this extension method to implement guard clauses without messy syntax:
That will work fine (no exception). Extension methods don't use virtual calls (i.e. it uses the "call" il instruction, not "callvirt") so there is no null check unless you write it yourself in the extension method. This is actually useful in a few cases:
etc
Fundamentally, calls to static calls are very literal - i.e.
becomes:
where there is obviously no null check.