<p>When I try this with a generic class where this.value is T:</p>

<pre><code>if (this.value.GetType() == typeof(int))
{
    ((int)this.value)++;
}
else
{
    throw new InvalidOperationException
            ("T must be an int to perform this operation");
}
</code></pre>

<p>I get a compile-time error: "Cannot convert type 'T' to 'int'"</p>

<p>What should I do to perform an integral operation on this.value when it's an int?</p>

<p>Note that this is just an example. The code does type conversions with generics, and "int" is just an example of one type for T. </p>

Unfortunately, it is very hard to convince the compiler about specific T implementations. One (nasty) approach is to cast to object in the middle (note this will box and unbox value-types):
```
```
int i = (int)(object)this.value;
i++;
this.value = (T)(object)i;
```
```
Ugly but it works. In .NET 3.5 I have some better wrappers for generic arithmetic,
here
. The Operator class is part of
MiscUtil
; at the simplest level, I suspect AddAlternative would work very well:
```
```
this.value = Operator.AddAlternative(this.value, 1);
```
```
This should infer the implicit <T,int> automatically, or you can add them yourself:
```
```
this.value = Operator.AddAlternative<T,int>(this.value, 1);
```
```
Benefit
: This is preferable to the original code as it doesn't actually care about the original T - it will work for any type (even your own) that supports "T +(T,int)".
I think there is also a ChangeType hiding around somewhere in there...
[edit] Collin K and others make a valid remark about the architectural implications - but being pragmatic there are times when the T really does matter that much... but I'd agree with avoiding this type of specialization unless
really
necessary. That said (as per  my comment on Collin's post), the ability to perform things like basic arithmetic (increment, Int32 division, etc) on (for example) a Matrix<T> [for T in decimal/float/int/double/etc] is often highly valuable.