Getting the name of the current class
I have the following class:
public class dlgBoughtNote : dlgSpecifyNone
{
public com.jksb.reports.config.cases.BoughtNoteReport _ReportSource;
public dlgBoughtNote()
{
btnPreview.Click += new EventHandler(Extended_LaunchReport);
this.Text = "Bought Note Print";
}
protected override void InitReport()
{
_ReportSource = new com.jksb.reports.config.cases.BoughtNoteReport(null);
ReportSourceName = _ReportSource;
}
}
Technically, if I called the following constructor dlgBoughtNote ()
public dlgBoughtNote()
{
btnPreview.Click += new EventHandler(Extended_LaunchReport);
this.Text = "Bought Note Print";
MessageBox.Show(this.Name);
}
I should get the result as "dlgBoughtNote" but I get it as "dlgSpecifyNone". Is there a way to get the current class name different from how I do it.
source to share
You can call GetType()
on this
to get the type of the instance, and use the Name
type property to get the current type name. The call this.GetType()
returns the type that was created, not the type that defines the currently executing method, so calling it on the base class will give you the type of the derived child class from which it was created this
.
A bit confusing ... here's an example:
public class BaseClass
{
public string MyClassName()
{
return this.GetType().Name;
}
}
public class DerivedClass : BaseClass
{
}
...
BaseClass a = new BaseClass();
BaseClass b = new DerivedClass();
Console.WriteLine("{0}", a.MyClassName()); // -> BaseClass
Console.WriteLine("{0}", b.MyClassName()); // -> DerivedClass
source to share
You never told us that yours was this.Name
. However, if you need to get the name of a runtime type, you can use any of the above answers. It's simple:
this.GetType().Name
in any combination you like.
However, I suppose what you were trying to do was to have a property, returning some specific value for any of the derived (or base) classes. Then you need to have at least a property protected virtual
that you need to override in each of the derived classes:
public class dlgSpecifyNone
{
public virtual string Name
{
get
{
return "dlgSpecifyNone";//anything here
}
}
}
public class dlgBoughtNote : dlgSpecifyNone
{
public override string Name
{
get
{
return "dlgBoughtNote";//anything here
}
}
}
But this is obviously unnecessary if it this.GetType().Name
solves this problem.
source to share