Home > DeveloperSection > Forums > Getting current class name including parent class name
Jayden Bell
Jayden Bell

Total Post:105

Points:739
Posted on    March-29-2014 4:14 AM

 C# C# 
Ratings:


 1 Reply(s)
 603  View(s)
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() { } }

}



Pravesh Singh

Total Post:411

Points:2881
Posted on    March-29-2014 7:02 AM

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

{

}


Don't want to miss updates? Please click the below button!

Follow MindStick