C# Getting Its Own Class Name

C# getting its own class name

Try this:

this.GetType().Name

Get Current Class Name

An instance would exactly be "current", the concept does not make much sense otherwise. If you just want the name of a known type that would be typeof(Class).Name.

Getting the class name

You can't there is no attribute available that does that. However because Log is private no external classes could call the function so you already know which class called it.

public SomeClass
{

//(snip)

private void Log(string logMessage, [CallerMemberName]string callerName = null)
{

if (logger.IsDebugEnabled)
{
string className = typeof(SomeClass).Name;

logger.DebugFormat("Executing Method = {1};{2}.{0}", logMessage, callerName, className);
}
}
}

Getting class name inside the class itself

When talking about non-static methods use Object.GetType Method which returns the exact runtime type of the instance (a reference to an instance of the Type Class):

this.GetType().Name

When talking about static methods, use MethodBase Class and its GetCurrentMethod Method :

Type t = MethodBase.GetCurrentMethod().DeclaringType;
//t.Name

However, see this post on SO for more info on this.

Get the name of a class as a string in C#

Include requires a property name, not a class name. Hence, it's the name of the property you want, not the name of its type. You can get that with reflection.

Getting Current Class's Name

The easiest way of getting the name of the current class' is probably this.GetType().Name.

Create an object knowing only the class name?

Since you know all classes will be coming from the same namespace, configure it once and use that:

<appConfig>
<SuperAppConfig handlerNamespace="BigCorp.SuperApp">
<Handler class="ClassB" />
</SuperAppConfig>
</appConfig>

Edit: I changed name to class to better denote the meaning of that attribute.

Create object instance of a class having its name in string variable

Having the class name in string is not enough to be able to create its instance.
As a matter of fact you will need full namespace including class name to create an object.

Assuming you have the following:

string className = "MyClass";
string namespaceName = "MyNamespace.MyInternalNamespace";

Than you you can create an instance of that class, the object of class MyNamespace.MyInternalNamespace.MyClass using either of the following techniques:

var myObj = Activator.CreateInstance(namespaceName, className);

or this:

var myObj = Activator.CreateInstance(Type.GetType(namespaceName + "." + className));

Hope this helps, please let me know if not.



Related Topics



Leave a reply



Submit