We use the .NET 2.0 framework with C# 3.0 (I think it’s the last version of C# which can run on the 2.0 version of the framework, correct me if I am wrong).
Is there something built into C# which can make this type of parameter validation more convenient?
public ConnectionSettings(string url, string username, string password,
bool checkPermissions)
{
if (username == null) {
throw new ArgumentNullException("username");
}
if (password == null) {
throw new ArgumentNullException("password");
}
if (String.IsNullOrEmpty(url)) {
throw new ArgumentException("Must not be null or empty, it was " +
(url == null ? url : "empty"), "url");
}
this.url = url;
this.username = username;
this.password = password;
this.checkPermissions = checkPermissions;
}
That sort of parameter validation becomes a common pattern and results in a lot of “almost boilerplate” code to wade through in our public methods.
If there is nothing built in. Are there any great free libraries which we could use?
I normally create static helper methods…
E.g.
Means you can condense your code down to something similar to below and just makes it a little tidier.
Or you can wrap it up as an extension method:
And use like:
And if you’re feeling really fancy, you could probably interrogate the parameter names by using reflection. Reflection’s kinda slow, so you’d only do this if you were going to throw an exception, but it saves you typing the literal parameter name all the time.