New Design Guideline: Null Paramarrays

Based on some security reviews we are doing on the system in general I added this implementation note to the Design Guidelines.    


Do be aware that null could be passed in for the paramarray.  You should validate that that paramarray is not null before processing (see section on parameter passing for more infomration).

      static void Main(string[] args)


            Sum(1, 2, 3, 4, 5); //result == 15

            Sum(null); //throws null reference exception


        static int Sum(params int[] values)


            int sum = 0;

            foreach (int i in values)


                sum += i;


            return sum;



Comments (6)

  1. In what situation would Main be passed a null argument array? The only way I can think of is via reflection.

  2. BillT says:

    > You should validate that that paramarray is not null before processing

    I agree.

    It would be good if foreach would handle null gracefully, too.

  3. Uwe Keim says:

    I disagree with BillT. foreach should fail on null, like it currently does.

  4. David – I went through the same confusion.

    But then I realized he wasn’t suggesting that the paramarray on Main was getting a null – he was suggesting that the paramarray on Sum was getting a null.

  5. Jeff Sink says:

    This seems completely wrong to me.

    For example,

    static int Sum(params object[] values)

    static int Sum2(params int[] values)

    if I call:

    Sum(null) I get an object[] of length 1, with one member: null, not a null refernce to the array.

    Sum2(null) though gives me a null reference for the array itself. It seems like this is inconsistent with the other uses, and seems wrong. Sum2( 1) means construct an int array of length one, and give it this value at the one location.

    Sum2(null) should throw a compile-time error saying null is inconsisitent with int type. Sum2(null, null) does not compile for this reason.

    Sum2(null) does not do the same thing as Sum(null), I guess because int is a ValueType. It is very unusual to have the syntax of an expression vary because of the types involved.

    So it seems like we special case when there is only one parameter, and it is null, and the declared type is a ValueType.

  6. Jeff, can you send me a repro? What build of the the C# compiler are you on? I just checked this on V1.1 and a recent whidby build and Sum(null) and Sum2(null) both throw an NullReferenceException.

    The C# compiler should always test whether the method is applicable in un-expanded form first. If it is, the compiler will not consider any expanded form. This rule is simple to understand. There is no special casing based on value-type vs reference-type. It’s all based on the existence (or not) of implicit conversions.

Skip to main content