Is there a simple attribute or data contract that I can assign to a function parameter that prevents null
from being passed in C#/.NET? Ideally this would also check at compile time to make sure the literal null
isn't being used anywhere for it and at run-time throw ArgumentNullException
.
Currently I write something like ...
if (null == arg)
throw new ArgumentNullException("arg");
... for every argument that I expect to not be null
.
On the same note, is there an opposite to Nullable<>
whereby the following would fail:
NonNullable<string> s = null; // throw some kind of exception
There's nothing available at compile-time, unfortunately.
I have a bit of a hacky solution which I posted on my blog recently, which uses a new struct and conversions.
In .NET 4.0 with the Code Contracts stuff, life will be a lot nicer. It would still be quite nice to have actual language syntax and support around non-nullability, but the code contracts will help a lot.
I also have an extension method in MiscUtil called ThrowIfNull which makes it a bit simpler.
One final point - any reason for using "
if (null == arg)
" instead of "if (arg == null)
"? I find the latter easier to read, and the problem the former solves in C doesn't apply to C#.Ok this reply is a bit late, but here is how I am solving it:
Use this exension method then you can treat null and empty string as the same thing.
E.g.
Not ideal I know as you have to remember to call default everywhere but it is one solution.
Check out the validators in the enterprise library. You can do something like :
Then in your code when you want to validate it:
not the prettiest but:
you could get more creative in the ContainsNullParameters method too:
of course you could use an interceptor or reflection but these are easy to follow/use with little overhead
I know I'm incredibly late to this question, but I feel the answer will become relevant as the latest major iteration of C# comes closer to release, then released. In C# 8.0 a major change will occur, C# will assume all types are considered not null.
According to Mads Torgersen:
So the resolution outlined by Mads, is:
An example of the desired feature:
The preview is available for Visual Studio 2017, 15.5.4+ preview.
I know this is a VERY old question, but this one was missing here:
If you use ReSharper you may use the Annotated Framework.