Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get name of surrounding class from within nested class

Tags:

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.

like image 601
Xarbrough Avatar asked Dec 19 '16 18:12

Xarbrough


People also ask

How do you access the inner class of an outer class?

Since inner classes are members of the outer class, you can apply any access modifiers like private , protected to your inner class which is not possible in normal classes. Since the nested class is a member of its enclosing outer class, you can use the dot ( . ) notation to access the nested class and its members.

Can a class contain another class in it C#?

In C#, a user is allowed to define a class within another class. Such types of classes are known as nested class.

Can we have public protected access modifiers in nested class?

You can also specify an access modifier to define the accessibility of a nested type, as follows: Nested types of a class can be public, protected, internal, protected internal, private or private protected.


1 Answers

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.

like image 167
Petter Hesselberg Avatar answered Sep 24 '22 16:09

Petter Hesselberg