Reputation: 2124
I was trying to use a generic function for 2 kinds of Collections, in which I call the method Add.
So below my Code:
using System;
using System.Collections;
namespace CollectionsApplication
{
class Program
{
static void AddElement<T>(ref T container, string key, string value)
{
container.Add(key, value);
}
static void Main(string[] args)
{
SortedList s1 = new SortedList();
Hashtable h1 = new Hashtable();
AddElement<SortedList>(ref s1, "001", "Zara Ali");
AddElement<Hashtable>(ref h1, "001", "Zara Ali");
}
}
}
and below the error :
error CS1061: 'T' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'T'
So Could this be performed and how to fix it if possible ?
Thank you in advance.
Upvotes: 1
Views: 57
Reputation: 7213
Or create an extension method:
public static class MyExtensions
{
public static void AddElement(this IDictionary container, string key, string value)
{
container.Add(key, value);
}
}
And usage:
SortedList s1 = new SortedList();
Hashtable h1 = new Hashtable();
s1.AddElement("001", "Zara Ali");
h1.AddElement("001", "Zara Ali");
Upvotes: 2
Reputation: 1863
Why not make it easier, like so?
using System;
using System.Collections;
namespace CollectionsApplication
{
class Program
{
static void AddElement(IDictionary container, string key, string value)
{
container.Add(key, value);
}
static void Main(string[] args)
{
SortedList s1 = new SortedList();
Hashtable h1 = new Hashtable();
AddElement(s1, "001", "Zara Ali");
AddElement(h1, "001", "Zara Ali");
}
}
}
Upvotes: 2
Reputation: 3231
The problem here is that T can be anything (e.g. an int) and isn't guaranteed to have an Add method.
You need to constrain T to something that has an Add method.
static void AddElement<T>(ref T container, string key, string value)
where T : IDictionary
{
container.Add(key, value);
}
Upvotes: 3