Getting current class name including parent class name

Total Post:110

Points:774
C# 
C#
 1001  View(s)
Ratings:
Rate this:

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() { } }
}
  1. Post:412

    Points:2888
    Re: Getting current class name including parent class name

    Hi Jayden,

    When you say GetType(), or equivalently this.GetType(), you get the actual type of the class. For example

    class A
    {
      public void Test()
      {
        Console.WriteLine(GetType().Name);
      }
    }
    class B : A
    {
    }

    and later:

    var myB = new B();

    myB.Test();   // writes B to the console

    I guess that's what polymorphism is all about.

    If you want always A, no polymorphism, simply say:

    class A
    {
      public void Test()
      {
        Console.WriteLine(typeof(A).Name);
      }
    }
    class B : A
    {
    }

      Modified On Apr-04-2018 04:47:37 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!