0

I have some already defined extension method like this:

    public static object Get(this IDictionary<string, object> dict, string key)
    {
        if (dict.TryGetValue(key, out object value))
        {
            return value;
        }

        return null;
    }

but if I try to use it with an instance of an

IDictionary <string, myClass>

it won't show up. I thought every class derived from object. Questions:

1) Why is this happening?

2) How could I make an extension method that includes all kinds of IDictionary?

user33276346
  • 1,501
  • 1
  • 19
  • 38

1 Answers1

1

This is perfectly working:

using System.Collections.Generic;

namespace ConsoleApp1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var dic = new Dictionary<string, object> {{"Test", 1}};
            var result = dic.Get("Test");
        }
    }

    public static class MyExtensions
    {
        public static object Get(this IDictionary<string, object> dict, string key)
        {
            if (dict.TryGetValue(key, out object value))
            {
                return value;
            }

            return null;
        }

        public static T Get<T>(this IDictionary<string, T> dict, string key)
        {
            if (dict.TryGetValue(key, out T value))
            {
                return value;
            }

            return default(T);
        }
    }
}
Bidou
  • 7,378
  • 9
  • 47
  • 70
  • Please review my question correction, as IDictionary is not working. – user33276346 Nov 18 '19 at 19:17
  • Use a `T` generic type instead of `object` in this case (see my edit) – Bidou Nov 18 '19 at 19:21
  • You are awesome! But why didn't it work out before? Shouldn't have the original extension method by available to IDictionary due to inheritance? I mean, isn't myClass an object? – user33276346 Nov 18 '19 at 19:34
  • 1
    @user33276346 See [Covariance and Contravariance (C#)](https://learn.microsoft.com/dotnet/csharp/programming-guide/concepts/covariance-contravariance/), [IDictionary<,> contravariance?](https://stackoverflow.com/q/12841458/150605), and [IDictionary in .NET 4 not covariant](https://stackoverflow.com/q/2149589/150605). – Lance U. Matthews Nov 18 '19 at 21:33