Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting current class name including parent class name?

Tags:

c#

.net

If I have a class B and C which inherits from A, is there something simpler than using StackFrame's GetFileName() (then parse out the ClassName.cs string)?

If I use this.GetType().Name, it won't return "A" when the code is executing in the parent class.

Sample Code

namespace StackOverflow.Demos
{
    class Program
    {
        public static void Main(string[] args)
        {
            B myClass = new C();
            string containingClassName = myClass.GetContainingClassName();
            Console.WriteLine(containingClassName); //should output StackOverflow.Demos.B
            Console.ReadKey();
        }
    }

    public class A { public A() { } }
    public class B : A { public B() { } }
    public class C : B { public C() { } }

}
like image 612
user1279437 Avatar asked Dec 26 '22 14:12

user1279437


1 Answers

var yourType = GetType();
var baseType = yourType.BaseType;

or alternatively:

var currentTypeName = new StackFrame(1, false).GetMethod().DeclaringType.Name;
like image 161
Daniel A. White Avatar answered Jan 17 '23 20:01

Daniel A. White