Frode Lillerud
Frode Lillerud

Reputation: 7394

Reflection to find nested class?

I've got a class that looks something like this:

public class Parent
{
    public class Subclass
    {
    }
}

and using reflection I'm trying to find the subclass

void main
{
    Parent p = new Parent();
    Type t = p.GetType();
    Type s = t.GetNestedType("Subclass"); //s is not set
}

This doesn't work because there apparently are no nested types. How can I find the type of the subclass? The reason I need to get s is to later call .GetMethod("someMethod").Invoke(...) on it.

Upvotes: 2

Views: 6024

Answers (1)

BFree
BFree

Reputation: 103740

I just tried the exact same thing, and it worked for me:

    public class ParentClass
    {
        public class NestedClass
        {

        }
    }

       private void button1_Click(object sender, EventArgs e)
        {
            Type t = typeof(ParentClass);
            Type t2 = t.GetNestedType("NestedClass");
            MessageBox.Show(t2.ToString());
        }

Are you sure the NestedClass is public?

Upvotes: 6

Related Questions