Eon
Eon

Reputation: 3974

Is there any way to overload the += operator in C#

I am trying to overload an += operator in my c# code, basically only to add a keyValuePair struct to a Hashtable (in this case, its a class inheriting from the Hashtable Class)

using System;
using System.Collections.Generic;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class Program
{
    private static void Main()
    {
        var x = new HashClass();
        x.Add("one", "one");
        x.Add("two", "two");

        var y = x + new KeyValuePair<string, string>("three", "three");
        y += new KeyValuePair<string, string>("four", "four");

        foreach (System.Collections.DictionaryEntry z in y)
        {
            Console.WriteLine(z.Key + " " + z.Value);
        }
    }
}

public class HashClass : System.Collections.Hashtable
{
    public static System.Collections.Hashtable operator +(HashClass itema, KeyValuePair<string, string> itemb)
    {
        itema.Add(itemb.Key, itemb.Value);
        return itema;
    }

    public static System.Collections.Hashtable operator +=(HashClass itema, KeyValuePair<string, string> itemb)
    {
        itema.Add(itemb.Key, itemb.Value);
        return itema;
    }

    public static implicit operator HashClass(KeyValuePair<string, string> item)
    {
        var x = new HashClass();
        x.Add(item.Key, item.Value);
        return x;
    }
}

The following errors pop up:

  1. Overloadable binary operator expected (I thought += was a valid operator. Are there special rules attached?
  2. Operator "+=" Cannot be applied to operands of type 'Hashtable' and 'KeyValuePair'- This kind of makes sense. My variably y has implicitly been converted now to a Hashtable. As a theory, I thought that this part will fail because y is not a HashClass

What else can I try to overload the += operator? Is this even possible?

Upvotes: 0

Views: 427

Answers (3)

Anton Selin
Anton Selin

Reputation: 3642

you can´t overload += operator. you can modify your code like this :

 var y = x + new KeyValuePair<string, string>("three", "three");
        y = y + new KeyValuePair<string, string>("four", "four");

and it will work as you want.

Upvotes: 0

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101701

You just need to overload the + operator because += is just a syntactic sugar, e.g:

x += 1

is equivalent to

x = x + 1;

Upvotes: 6

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73492

No, You can't overload += operator. But you can overload + operator.

Assignment operators cannot be overloaded, but +=, for example, is evaluated using +, which can be overloaded.

From Msdn

Upvotes: 1

Related Questions