Daniel Williams
Daniel Williams

Reputation: 9304

How to test if a reflected field's type is, or inherits from, a specified type

I am iterating through the FieldInfo of a class. I want to be able to test if a given field is of a certain type.

The specific issue is that I want to know all fields that are derived from SortedList. So they are not exactly SortedList, but each one IS a SortedList. Given the field's FieldInfo, how do I test this?

Upvotes: 3

Views: 1939

Answers (4)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

You can use IsAssignableFrom method to perform this test, like this:

var isSortedList = typeof(SortedList).IsAssignableFrom(fieldInfo.FieldType);

Upvotes: 10

D Stanley
D Stanley

Reputation: 152491

bool canCast = (fieldInfo.FieldType == typeof(SortedList) ||
               (fieldInfo.FieldType.IsSubclassOf(typeof(SortedList)));

Upvotes: 0

ΩmegaMan
ΩmegaMan

Reputation: 31576

Instead of looking for the SortedList as the type, you can also look for interfaces such as IDictionary, ICollection which SortedList derives from. I provide an interesting read on my blog which gives an example of reflecting for an interface:

Reflect Interface from Unknown Assembly in C#

HTH (From HR down south of you ;-) )

Upvotes: 0

M.Babcock
M.Babcock

Reputation: 18965

if ((fieldInfo.FieldType == typeof(SortedList)) || fieldInfo.FieldType.IsSubclassOf(typeof(SortedList))
    Console.WriteLine("Field {0} is of type {1}", fieldInfo.Name, typeof(blah.Name));

This code is untested but is roughly what I have used before.

Upvotes: 0

Related Questions