Is there a way of explicitly specifying that a return value can be null using Code Contracts?
My worry is that methods without a Contract.Ensures(Contract.Result<object>() != null)
may be incorrectly 'fixed' in the future to include the post-condition, even though the original intention may have been to allow null results.
If there are any other post-conditions then these will indicate that null
is a valid return value. For example, if a method should return a positive value but uses null
if an error occurs:
Contract.Ensures(Contract.Result<int?>() == null || 0 <= Contract.Result<int?>());
If you're worried about regression, though, the best solution might be to add a unit test for an expected null
return value.
If you are using resharper you can get it to produce warnings by marking methods with the CanBeNull attribute as described here: http://blogs.jetbrains.com/dotnet/2010/11/resharper-nullreferenceexception-analysis-and-its-contracts/
Its done using some resharper classes, but convieniently you dont have to reference a library - theres a button in the options to let you get your hands on the annotations. Little thing to be careful of: you need to keep the namespace they are in the same - it appears the actual marking is done by fully qualified name (so putting the classes in your own ns and using them wont produce the warnings you want).
This is very useful for properties that can be null on classes (eg where a user decision is yet to be made/can be removed) but where the assignment is a data object that means it is inappropriate to use the null object pattern. We've got one of those in a project im working on which always trips up new coders who dont realise it can be null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With