Wildcard equivalent in C# generics

AxiomaticNexus picture AxiomaticNexus · Mar 22, 2013 · Viewed 20.7k times · Source

Let's say I have a generic class as follows:

public class GeneralPropertyMap<T>
{
}

In some other class I have a method that takes in an array of GeneralPropertyMap<T>. In Java, in order to take in an array that contains any type of GeneralPropertyMap the method would look like this:

private void TakeGeneralPropertyMap(GeneralPropertyMap<?>[] maps)
{
}

We use the wildcard so that later we can call TakeGeneralPropertyMap passing a bunch of GeneralPropertyMap with any type for T each, like this:

GeneralPropertyMap<?>[] maps = new GeneralPropertyMap<?>[3];
maps[0] = new GeneralPropertyMap<String>();
maps[1] = new GeneralPropertyMap<Integer>();
maps[2] = new GeneralPropertyMap<Double>();
//And finally pass the array in.
TakeGeneralPropertyMap(maps);

I'm trying to figure out an equivalent in C# with no success. Any ideas?

Answer

Daniel A.A. Pelsmaeker picture Daniel A.A. Pelsmaeker · Mar 22, 2013

Generics in C# make stronger guarantees than generics in Java. Therefore, to do what you want in C#, you have to let the GeneralPropertyMap<T> class inherit from a non-generic version of that class (or interface).

public class GeneralPropertyMap<T> : GeneralPropertyMap
{
}

public class GeneralPropertyMap
{
    // Only you can implement it:
    internal GeneralPropertyMap() { }
}

Now you can do:

private void TakeGeneralPropertyMap(GeneralPropertyMap[] maps)
{
}

And:

GeneralPropertyMap[] maps = new GeneralPropertyMap[3];
maps[0] = new GeneralPropertyMap<String>();
maps[1] = new GeneralPropertyMap<Integer>();
maps[2] = new GeneralPropertyMap<Double>();
TakeGeneralPropertyMap(maps);