views:

2368

answers:

4

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
+8  A: 

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#.

Jon Skeet
> There's nothing available at compile-time, unfortunately. > ... > It would still be quite nice to have actual language syntax and support around non-nullabilityI agree. I would also like to see compile-time errors being raised.
AndrewJacksonZA
+1  A: 

Check out the validators in the enterprise library. You can do something like :

private MyType _someVariable = TenantType.None;
[NotNullValidator(MessageTemplate = "Some Variable can not be empty")]
public MyType SomeVariable {
    get {
     return _someVariable;
    }
    set {
     _someVariable = value;
    }
}

Then in your code when you want to validate it:

Microsoft.Practices.EnterpriseLibrary.Validation.Validator myValidator = ValidationFactory.CreateValidator<MyClass>();

ValidationResults vrInfo = InternalValidator.Validate(myObject);
Chris Lively
A: 
public void foo(int? id, string name)
{
    if (id == null)
    {
       throw new ArgumentNullException("id");
    }
    if (name == null)
    {
       throw new ArgumentNullException("name");
    }

    this.foo = id.Value;
    this.fooName = name;

}

there u go, otherwhise just define other statement.

Bas Hermens
+1  A: 

Have a look here:

http://www.hutteman.com/weblog/2004/06/02-181.html

FireFart