So I setup C# parameter validation using the method described in this blog post. Everything works great for strings for which I have this extension method setup at the base of it all:
public static ArgumentEx<T> NotEmptyString<T>(this ArgumentEx<T> arg) where T : class
{
if (string.IsNullOrWhiteSpace(arg.Value.ToString()))
{
throw new ArgumentException(string.Format("{0} cannot be empty.", arg.Name));
}
return arg;
}
However, when I try and add an extension method for ints to determine if they are less than or equal to zero such as this:
public static ArgumentEx<T> NotZeroOrLess<T>(this ArgumentEx<T> arg) where T : class
{
if (Convert.ToInt32(arg.Value.ToString()) <= 0)
{
throw new ArgumentException(string.Format("Please make sure {0} is greater than zero.", arg.Name));
}
return arg;
}
I get this error when I try and call it like so userId.RequireThat("userId").NotZeroOrLess();
The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method
Like I said, doing name.RequireThat("name").NotEmptyString(); works fine, as name is a string. I've tried specifying the type for the generic like so:
userId.RequireThat<int>("userId").NotZeroOrLess();
But I get the same error. I have to admit, I'm not too well versed with generics. Can someone explain why this error is occurring? Thanks ahead of time.