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.
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.
In C#, a user is allowed to define a class within another class. Such types of classes are known as 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With