Steve
Steve

Reputation: 923

substitute system.reflection for "this"

I have a method I am trying to make a little more easy to widely deploy.

NHibernateISession.log4netLogFileEntry("DEBUG", "hello",
    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);

I would like to reduce the System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName to a simple this.

But how do I get the FullName from this.FullName?

Just fyi in case it helps you: System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName gives you the

<namespace>.<namespace>.<namespace>.<class>

Upvotes: 2

Views: 250

Answers (2)

Steve
Steve

Reputation: 923

System.Exception.StackTrace is an excellent substitute for what I was attempting. In fact, it is even better. And all I have to do is: try { ... } catch (Exception e) { myfunction(e); } and: MyFunction(Exception e) { log(e.StackTrace) }

Upvotes: 0

D Stanley
D Stanley

Reputation: 152566

this is an object - System.Reflection.MethodBase.GetCurrentMethod().DeclaringType is a type. If you want to get the full name of the type of this then use

this.GetType().FullName

But note that they aren't equivalent. The longer one returns the type that declares the method. If the actual object is a subclass then you'll get the sub-type name. It also won't work for static methods, while System.Reflection.MethodBase.GetCurrentMethod().DeclaringType would.

If you actually want the type that declares the method in question then

System.Reflection.MethodBase.GetCurrentMethod().DeclaringType

is the correct approach. There is no keyword or shortcut that can be used in its place generically.

Upvotes: 3

Related Questions