1

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.

2 Answers 2

1

Have you tried to remove where T : class from your extension method public static ArgumentEx<T> NotZeroOrLess<T>(this ArgumentEx<T> arg) where T : class?

Sign up to request clarification or add additional context in comments.

1 Comment

That did it, and I understand these things more fully after reading the links Tomas posted as well. However, will removing this cause any problems in the future that I should be aware of?
1

It is throwing error because you defined class constraint, but int is not a class, it is a value type - struct. Read basics http://msdn.microsoft.com/en-us/library/d5x73970.aspx.

Read Why can't I use System.ValueType as a generics constraint? for more info.

1 Comment

Thanks for the links Tomas. These things make a little bit more sense now :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.