Monday, 27 April 2009

Method with arbitrary number of parameters in C#

One can also create a method with variable number of parameters in C#. It is needed, for example, when you have such logic, where you need to take value from one place, if it is not null, or from the other, or from the third place, if the first two are nulls, and so on. This can help:

public static T FirstNotNull<T>(params Nullable<T>[] objects) where T : struct
{
  foreach (Nullable<T> obj in objects)
    if (obj.HasValue) return obj.Value;
  return default(T);
}

Reserved word params shows, that we deal with an array of parameters. This parameter can only be the last one in a function. You can put other types of parameters before, but no after.

The function can be called like that:

HelperClass.FirstNotNull<int>(firstValue, secondValue, thirdValue, fourthValue);

The first not null value of these four is returned, or default value of the type, if all are nulls.