Himberjack
Himberjack

Reputation: 5792

How to determine if class inherits Dictionary<,>

I have

public class SerializableDictionary<TKey, TValue>
    : Dictionary<TKey, TValue>, IXmlSerializable

And I want to check if an object is SerializeableDictionary (of any generic types).

For that I tried:

type == typeof(SerializableDictionary<,>)
or type.isSubclass()
or typeof(SerializableDictionary<,>).isAssigneableFrom(type)

nothing works. How can I tell if the type is SerializableDictionary or any type?

tnx!

Upvotes: 0

Views: 259

Answers (2)

Eser
Eser

Reputation: 12546

var obj = new List<int>(); // new SerializableDictionary<string, int>();
var type = obj.GetType();

var dictType = typeof(SerializableDictionary<,>);
bool b = type.IsGenericType && 
         dictType.GetGenericArguments().Length == type.GetGenericArguments().Length &&
         type == dictType.MakeGenericType(type.GetGenericArguments());

Upvotes: 2

Magnus
Magnus

Reputation: 46929

I would probably create an interface ISerializableDictionary and let SerializableDictionary<TKey, TValue> inherit from that.

public interface ISerializableDictionary : IDictionary
{
}

public class SerializableDictionary<TKey, TValue>
    : Dictionary<TKey, TValue>, IXmlSerializable, ISerializableDictionary

Then just:

var res = dic is ISerializableDictionary;

Upvotes: 1

Related Questions