Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a function that returns the current class/method name? [duplicate]

Tags:

c#

In C#, is there a function that returns the current class/method name?

like image 672
Craig Johnston Avatar asked Mar 22 '11 05:03

Craig Johnston


People also ask

Can a method have same name as its class?

Yes, It is allowed to define a method with the same name as that of a class.

Can we define a method name same as class name in Java?

We can have a method name same as a class name in Java but it is not a good practice to do so. This concept can be clear through example rather than explanations. In the below example, a default constructor is called when an object is created and a method with the same name is called using obj.

How do you find the current method name?

The current method name that contains the execution point that is represented by the current stack trace element is provided by the java. lang. StackTraceElement. getMethodName() method.

How do you return a method name in Java?

Method Class | getName() Method in Java Method class is helpful to get the name of methods, as a String. To get name of all methods of a class, get all the methods of that class object. Then call getName() on those method objects. Return Value: It returns the name of the method, as String.


2 Answers

Current class name:

this.GetType().Name; 

Current method name:

using System.Reflection;  // ...  MethodBase.GetCurrentMethod().Name; 

Since you're using this for logging purposes, you may also be interested in getting the current stack trace.

like image 104
Cameron Avatar answered Sep 22 '22 22:09

Cameron


System.Reflection.MethodBase.GetCurrentMethod()

like image 24
Gabe Avatar answered Sep 19 '22 22:09

Gabe