Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8341313
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T05:26:41+00:00 2026-06-09T05:26:41+00:00

I know there are many question on SO like this Operator ‘whatever’ cannot be

  • 0

I know there are many question on SO like this
"Operator 'whatever' cannot be applied to operands of type 'T' (whatever may be ++, += or <= etc. etc. But bear with me, I wanna ask something different.

Let’s say I have this code

public class GenericCls<T> where T : struct
{
    public static T AddValues(params T[] values)
    {
        T sum = default(T);
        if (values != null)
        {
            for (int i = 0; i < values.Length; i++)
            {
                sum += values[i];
            }
        }
        return sum;
    }
}

even though I’ve made my type struct, and value type I get the error
Operator '+=' cannot be applied to operands of type 'T' and 'T'

If I try to be subtle and apply the ValueType constraint, it says
Constraint cannot be special class 'System.ValueType'

If I try to turn the parameter in for loop to type T, and do this..

public class GenericCls<T> where T : struct, IComparable<T>, IEquatable<T>
{
    public static T AddValues(params T[] values)
    {
        T sum = default(T);
        if (values != null)
        {
            for (T i = default(T); i < values.Length; i++)
            {
                sum += values[i];
            }
        }
        return sum;
    }
}

I still get errors

Operator '<' cannot be applied to operands of type 'T' and 'int'
Operator '++' cannot be applied to operand of type 'T'
Cannot implicitly convert type 'T' to 'int'

No matter what, I can’t get it to work. I am using VS2010 (C# 4.0, .NET 4.0). So I wanna know when C# 5.0 would be finally released with VS2012 (as far as I know they are still in beta stage right?) would it take care of these issues? Or are we again left with so many restriction on usage of Generics?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T05:26:42+00:00Added an answer on June 9, 2026 at 5:26 am

    It is possible without language improvements, but you have to use some tricks and cannot apply it to existing numeric types, but have to create new ones. One of them is the curiously recurring pattern class C<T> : where T : C<T>. Another trick is to use static delegates for the operations. I define a numeric class like this (for the sake of simplicity I only define the addition):

    public abstract class Numeric<T>
        where T : Numeric<T>
    {
        public static Func<T, T, T> Add;
    
        public static T operator +(Numeric<T> x, Numeric<T> y)
        {
            if (x == null) {
                return (T)y;
            }
            if (y == null) {
                return (T)x;
            }
            return Add((T)x, (T)y);
        }
    }
    

    Note that we have to specify at least one type as Numeric<T> when overloading the operator (one type must always be the class that overloads the operator). Note also that we can cast Numeric<T> to T because of the generic constraint where T : Numeric<T>

    Now we can declare a calculator like this. Since Numeric<T> overloads the + operator, we can use += here.

    public class Calculator<T> where T : Numeric<T>
    {
        public static T AddValues(params T[] values)
        {
            T sum = default(T);
            if (values != null) {
                for (int i = 0; i < values.Length; i++) {
                    sum += values[i];
                }
            }
            return sum;
        }
    }
    

    Now lets define a concrete Numeric class. In the static constructor we define the static Add delegate. Since the operators are static, this delegate must be static as well because it is called from within the operator method, and since static members cannot be virtual, we must use this delegate-trick.

    public class Complex : Numeric<Complex>
    {
        static Complex()
        {
            Add = (x, y) => new Complex(x.Re + y.Re, x.Im + y.Im);
        }
    
        public double Re { get; private set; }
        public double Im { get; private set; }
    
        public Complex(double re, double im)
        {
            Re = re;
            Im = im;
        }
    
        public override string ToString()
        {
            return String.Format("({0}, {1})", Re, Im);
        }
    }
    

    Now lets test this tricky construction

    static class Test
    {
        public static void AddComplexNumbers()
        {
            // Using the calculator
            var numbers = new Complex[] { new Complex(2, 7), new Complex(6, -2) };
            var result = Calculator<Complex>.AddValues(numbers);
            Console.WriteLine(result); // ==> (8, 5)
    
            // Directly
            var c1 = new Complex(2, 7);
            var c2 = new Complex(6, -2);
            result = c1 + c2;
            Console.WriteLine(result); // ==> (8, 5)
    
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I will preface this question with the disclaimer that I know there are many
I know there are already many questions like mine but I found no answer
Firstly I know that there are many question and solutions to correct thread marshalling
It's my first question on SO. I know that there were many topics on
I know that there are many different questions about this sort of topic on
I know that there are many API's like JSON, Facebook, Twitter etc for developing
This may seem like an obvious (or not so obvious) question, but let me
I know there are many questions and answers about this, but I am looking
First of all, there are many questions just like this, and perhaps some OPs
I know there are multiple questions about this same question but I couldn't find

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.