Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through method's parameters for validation purposes

Tags:

c#

.net

null

I've been thinking that it would be useful to be able to do such a thing, for example, to check the parameters for null references and eventually throw an exception.
This would save some typing and also would make it impossible to forget to add a check if a new parameter is added.

like image 693
RobSullivan Avatar asked Oct 01 '09 12:10

RobSullivan


1 Answers

Well, not unless you count:

public void Foo(string x, object y, Stream z, int a)
{
    CheckNotNull(x, y, z);
    ...
}

public static void CheckNotNull(params object[] values)
{
    foreach (object x in values)
    {
        if (x == null)
        {
            throw new ArgumentNullException();
        }
    }
}

To avoid the array creation hit, you could have a number of overloads for different numbers of arguments:

public static void CheckNotNull(object x, object y)
{
    if (x == null || y == null)
    {
        throw new ArgumentNullException();
    }
}

// etc

An alternative would be to use attributes to declare that parameters shouldn't be null, and get PostSharp to generate the appropriate checks:

public void Foo([NotNull] string x, [NotNull] object y, 
                [NotNull] Stream z, int a)
{
    // PostSharp would inject the code here.
}

Admittedly I'd probably want PostSharp to convert it into Code Contracts calls, but I don't know how well the two play together. Maybe one day we'll be able to write the Spec#-like:

public void Foo(string! x, object! y, Stream! z, int a)
{
    // Compiler would generate Code Contracts calls here
}

... but not in the near future :)

like image 124
Jon Skeet Avatar answered Sep 25 '22 15:09

Jon Skeet