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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With