C# generics - what is gained by making a wrapper class generic?

With the generic version a method could take a parameter of type Request<FooOperation>. Passing in an instance of Request<BarOperation> would be invalid.
So, the generic version enables methods to ensure they get a request for the correct operation.


In addition to all the other good answers, I'll add that the generic version does not take the boxing penalty if you happen to construct Request<T> with a T that is a value type that implements IOperation. The non-generic version boxes every time.


In the case you have given above, it is hard to say what benefit you get, it would depend on how this is to be used in your code base, but consider the following:

public class Foo<T> 
    where T : IComparable
{
    private T _inner { get; set; }

    public Foo(T original)
    {
        _inner = original;
    }

    public bool IsGreaterThan<T>(T comp)
    {
        return _inner.CompareTo(comp) > 0;
    }
}

against

public class Foo             
{
    private IComparable  _inner { get; set; }

    public Foo(IComparable original)
    {
        _inner = original;
    }

    public bool IsGreaterThan(IComparable  comp)
    {
        return _inner.CompareTo(comp) > 0;
    }
}

If you then had a Foo<int>, you probably wouldn't want to compare it to a Foo<string>, but would have no way of locking that down using the non-generic version.

Tags:

C#

.Net

Generics