1

I'm struggling to define an extension method for a Dictionary that has a List in its Value.

I've done this:

public static bool MyExtensionMethod<TKey, TValue, K>(this IDictionary<TKey, TValue> first, IDictionary<TKey, TValue> second) where TValue : IList<K>
    {
        //My code...
    }

To use it I have this class:

public class A
{
    public Dictionary<int, List<B>> MyPropertyA { get; set; }
}

public class B
{
    public string MyPropertyB { get; set; }
}

But when I do this:

var a1 = new A();
var a2 = new A();
var a = a1.MyPropertyA.MyExtensionMethod(a2.MyPropertyA)

I get this error 'the type arguments for method '...' cannot be inferred from the usage'

How should I define the method or call it? Thanks in advance!!

joacoleza
  • 775
  • 1
  • 9
  • 26

1 Answers1

1

Without generic constraint, it is much easier to define:

public static class Extensions
{
    public static bool MyExtensionMethod<TKey, TValue>(
        this IDictionary<TKey, List<TValue>> first,
        IDictionary<TKey, List<TValue>> second)
    {
        return true;
    }
}

public class A
{
    public Dictionary<int, List<B>> MyPropertyA { get; set; }
}
public class B
{
    public string MyPropertyB { get; set; }
}
class Program
{
    static void Main(string[] args)
    {

        var a1 = new A();
        var a2 = new A();
        var a = a1.MyPropertyA.MyExtensionMethod(a2.MyPropertyA);
    }
}

I am not sure with you would need the 3rd generic argument K. This method should be enough for your usage.

On a side note, you should know about the Lookup class, which is kind of a Dictionary with a Key and a List of stuff, except it is immutable.

public static class Extensions
{
    public static bool MyExtensionMethod<TKey, TValue>(
        this ILookup<TKey, TValue> first,
        ILookup<TKey, TValue> second)
    {
        return true;
    }
}

public class A
{
    public ILookup<int, B> MyPropertyA { get; set; }
}
public class B
{
    public string MyPropertyB { get; set; }
}
class Program
{
    static void Main(string[] args)
    {

        var a1 = new A();
        var a2 = new A();
        var a = a1.MyPropertyA.MyExtensionMethod(a2.MyPropertyA);
    }
}
Community
  • 1
  • 1
Cyril Gandon
  • 16,830
  • 14
  • 78
  • 122