Reputation: 3974
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:
y
has implicitly been converted now to a Hashtable. As a theory, I thought that this part will fail because y
is not a HashClassWhat else can I try to overload the += operator? Is this even possible?
Upvotes: 0
Views: 427
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
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
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.
Upvotes: 1