2

I am writing a generic method for addition of integers, float, double

public T  Swap<T>( T value1,  T value2)
{
    T temp;
    temp = value1 +value2;
    return temp;
}

I am getting an error:

Operator '+' cannot be applied to operands of type 'T' and 'T'

I am using VS 2005, can anyone tell me how to achive it?

2
  • 3
    It can't be done. There's no way to constrain a generic type to be numeric, which would (hand-wave) be what is necessary to have this work. Commented Jul 30, 2011 at 15:31
  • Didn't Mono do something like interfaces for basic arithmetic, with compiler support for the basic types? I wonder how long it'll take for Microsoft to realize it would be a nice addition in their release as well. Commented Jul 30, 2011 at 15:36

1 Answer 1

6

You can't do this directly. Generics in .NET just don't support it. However, there are other options available:

  • In C# 4, you can use dynamic typing:

    public static T Sum<T>(T value1,  T value2)
    {
        dynamic temp = value1;
        temp += value2;
        return temp;
    }
    

    EDIT: I hadn't noticed that you were using VS2005. Do you really have to? Any chance you could upgrade to something a little more recent?

  • Marc Gravell wrote code in MiscUtil to do this pretty efficiently with delegates. See the usage page for more information. The implementation in MiscUtil uses C# 3 and .NET 3.5, but I believe Marc has a separate implementation of the same ideas in .NET 2 using DynamicMethod. We can ping him to check if you need that...

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

1 Comment

I didn't think you could do C# 4 in VS2005.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.