Get name of surrounding class from within nested class

1.9k views Asked by At

I have a nested class within an outer class and from within the inner class I would like to get the name of the outer class via reflection at runtime.

public abstract class OuterClass // will be extended by children
{
    protected class InnerClass // will also be extended
    {
        public virtual void InnerMethod()
        {
            string nameOfOuterClassChildType = ?;
        }
    }
}

Is this possible in c#?

Edit: I should add, that I want to use reflection and get the name from a child class which extens from OuterClass, which is the reason, I don't know the concrete type at compile time.

1

There are 1 answers

1
Petter Hesselberg On BEST ANSWER

Something like this should parse out the name of the outer class:

public virtual void InnerMethod()
{
    Type type = this.GetType();

    // type.FullName = "YourNameSpace.OuterClass+InnerClass"

    string fullName = type.FullName;
    int dotPos = fullName.LastIndexOf('.');
    int plusPos = fullName.IndexOf('+', dotPos);
    string outerName = fullName.Substring(dotPos + 1, plusPos - dotPos - 1);

    // outerName == "OuterClass", which I think is what you want
}

Or, as @LasseVKarlsen proposed,

string outerName = GetType().DeclaringType.Name;

...which is actually a better answer.