0

Is it possible to refer to the name of the class that a piece of code is in?

For example when adding logging statements with log4net we initialise the log like this in each class...

private static readonly ILog Log = LogManager.GetLogger(typeof(EmploymentCorrectionUpdate));

Where 'EmploymentCorrectionUpdate' is the name of the class containing the code.

It would be a lot easier if the class name could be retrieved generically.

Please Note: This is a static field.

Simon Keep
  • 9,886
  • 9
  • 63
  • 78

4 Answers4

3

this.GetType() should do the trick, if you are not in a static context.

If you are in a static context, use

Type t = MethodBase.GetCurrentMethod().DeclaringType

(from .NET: Determine the type of “this” class in its static method)

Community
  • 1
  • 1
magnattic
  • 12,638
  • 13
  • 62
  • 115
2

yeah funny enough we use it for logging too, although I don't like using reflection for these purposes:

MethodInfo.GetCurrentMethod().DeclaringType.Name;
Ruslan
  • 9,927
  • 15
  • 55
  • 89
  • Thanks TSar will this work for static fields that are not in a method too? – Simon Keep Sep 08 '11 at 15:13
  • Actually, causes a resharper warning 'Access to a static member of a type via a derived type' Need to use MethodBase instead. I've got to give it to atticae, sorry dude. – Simon Keep Sep 08 '11 at 15:26
1

For an instance method it's easy (this.GetType()), but you need a static, class-level method.

I think that's difficult (or slow). If there was an easy/quick way, the log4net developers would have used it.

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
0

You can use the below code for getting the class name.

MethodBase method = frame.GetMethod(); method.DeclaringType.Name

Shashi
  • 71
  • 3