I came up with a little - as far as I'm concerned - cool library consisting of extension methods used to guard input parameters of public methods.
It's always a good idea to validate arguments of public methods and throw exceptions if the validation fails. If you require that a parameter is not null, throw an "ArgumentNullException" if the specified argument is null, this makes debugging so much easier and helps other developers that uses your API. To do this in all public methods is a painstaking and repetitive job but my little library makes it just a bit easier.
For example to validate that the string argument of the following method is not null or empty we'd have to write code something like this:
Now with my extension methods you'd instead write the following:
We can perform other validations as well, for example, we can validate that a value is within a given range:
By using generics and generic constraints the extension methods only appear on values of types they are applicable to. For example the method that checks if a value is within a specified range is only applicable to values of types that implements the IComparable(T)-interface.
This means that the method will only be shown in the Intellisense on values that it can be applied to:
Note that in the first case the variable "o" is of the type "object", and the only applicable method is the one that checks for null. In the second case "o" is of the type "int" and now there are two applicable methods, the one that checks if arguments that implements IComparable(T) are within a specified range and the one that checks if an index (int) is within a specified range. Since int is a value type it can't be null so the ExceptionIfNull(T)-method is not applicable, this is little piece of magic is accomplished by the generic constraint "where T : class" that set on the ExceptionIfNull(T)-method.
And here's the code: