In .NET, can you use reflection to get all non-inherited methods of a class?

Mark A. Donohoe picture Mark A. Donohoe · May 4, 2011 · Viewed 9.5k times · Source

Because of this issue here, I'm trying to write a custom JsonConverter that handles cases where you subclass a list or a collection, then add extra properties to it. As such, one approach would be to ignore all base-class properties and only serialize those in the defined class. (Technically this won't work because if you subclass that subclass you break the serialization, but it did make me wonder...)

Is it possible via reflection (well I know the answer is 'yes' because Reflector does exactly that, but I don't know how) to get only the members that are defined on the class itself as opposed to those that were inherited? For instance...

public class MyBaseClass
{
    public string BaseProp1 { get; set; }
    public string BaseProp2 { get; set; }
}

public class MySubClass : MyBaseClass
{
    public string SubProp1 { get; set; }
    public string SubProp2 { get; set; }
}

In this case, I want to reflect on MySubClass and only get SubProp1 and SubProp2 while ignoring BaseProp1 and BaseProp2. So can that be how is that done?

M

Answer

Ankur picture Ankur · May 4, 2011

While calling "GetMembers" method to get the members of the Type, you can specify "DeclaredOnly" in binding flag.