C# getting its own class name
Try this:
this.GetType().Name
Get The Class Name From an Object Variable
GetType()
should provide the proper System.Type
of the object at runtime.
For example, this prints "StringBuilder"
:
StringBuilder sbText = new StringBuilder();
Object oMyObject = sbText;
Console.WriteLine(oMyObject.GetType().Name);
Note that if you just want to check for a specific class type, is
(or as
) often works more cleanly than getting a Type
:
StringBuilder sbText = new StringBuilder();
Object oMyObject = sbText;
//...
StringBuilder sb = oMyObject as StringBuilder;
if (sb != null)
{
// oMyObject was a StringBuilder - you can use sb as needed:
sb.AppendText("Foo");
}
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
.
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.
Get the name of the class where the object was created
There is no nice way to do that. You can access the stack-frames (just look at the second frame, rather than the first) - but that is expensive and brittle. You could use optional caller-member-name attributes (being explicit from TestMethod1
) to get hold of "Method1"
, but not the "Class1"
part. One other option would be to pass in an object (or just the name) explicitly; for example:
private void Method1()
{
var obj=new TestClass();
obj.TestMethod1(this);
}
public void TestMethod1(object caller=null,
[CallerMemberName] string callerName=null)
{
TestMethod2(caller??this,callerName??"TestMethod1");
}
private void TestMethod2(object caller=null,
[CallerMemberName] string callerName=null)
{
string callerName = ((caller??this).GetType().Name) + "." + callerName
//get the calling class
}
but I have to confess that is pretty ugly
Perhaps better would be to question why you need this in the first place.
Get class name from the class who extend it
You can use object.GetType
which will always return the type on top in the hierarchy (so the last deriving class):
public string Request
{
get
{
return this.GetType().Name;
}
}
Name
will return the short type name, without the namespace. If you want that too, you should use FullName
.
Reflection: Get Class name from supplied property value
I wouldn't create a method for that, as you need an instance to call that method. You could however create a static property which returns the type. Maybe an attribute would even be better.
I created a fiddle as an example: https://dotnetfiddle.net/IweLy7
It relies on scanning the assembly for relevant types. As stated by the other answer you may have to check additional assemblies for your usecase.
How to get the name of class where an object is initialized c#
This requirement can be satisfied without inheritance or passing the object; we can get the name of the class that calls the constructor from within the body of the constructor by examining the stack.
public class A
{
private string _createdBy;
public void SomeAction()
{
Console.WriteLine("I was declared in class [{0}]", _createdBy);
}
public A()
{
var stackFrame = new StackFrame(1);
var method = stackFrame.GetMethod();
_createdBy = method.DeclaringType.Name;
}
}
In terms of performance, I am assuming that you are not creating many instances of these objects. You could also predicate this on whether you are doing a DEBUG build or on some other setting, so that this stuff is skipped entirely in your production executables.
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);
}
}
}
Related Topics
Can a Bool Read/Write Operation Be Not Atomic on X86
Convert Wstring to String Encoded in Utf-8
Conversion from String Literal to Char* Is Deprecated
Why Do We Need to Use Boost::Asio::Io_Service::Work
Why Should Default Parameters Be Added Last in C++ Functions
Allowing Signed Integer Overflows in C/C++
Which Is Better Option to Use for Dividing an Integer Number by 2
When Should I Use C++14 Automatic Return Type Deduction
Does C++ Pass Objects by Value or Reference
Loop Unrolling to Achieve Maximum Throughput with Ivy Bridge and Haswell
Dll Load Library - Error Code 126
What Is the Datatype of String Literal in C++
Where Are Temporary Object Stored
How to Get the Digits of a Number Without Converting It to a String/ Char Array
Convert Std::Tuple to Std::Array C++11
Why Does 'Std::Vector<Int> B{2};' Create a 1-Element Vector, and Not a 2-Element One