Tuesday 6 November 2012

GetType vs MethodBase.GetCurrentMethod().DeclaringType


Effective logging of what class is what is a real concerns and can save you hours of debugging and searching through lots of code. Knowing when to use GetType or MethodBase.GetCurrentMethod().DeclaringType can be vital when using abstract classes. 


Below is a code sample that uses the both in overridden and non-overridden methods.


 class Program
    {
        static void Main(string[] args)
        {
            var msgClass = new Topclass();
            msgClass.message1();
            msgClass.message2();
            msgClass.message3();
            Console.ReadKey();
        }
    }

    public class Topclass : BaseMe
    {
        public void message3()
        {
             Console.WriteLine("TOPCLASS Message 3: " + this.GetType().ToString());
             Console.WriteLine("TOPCLASS Message 3: " + MethodBase.GetCurrentMethod().DeclaringType);
        }
        public override void  message2()
        {
            Console.WriteLine("OVERRIDE Message 2: " + this.GetType().ToString());
            Console.WriteLine("OVERRIDE Message 2: " 
                       + MethodBase.GetCurrentMethod().DeclaringType);
        }
    }
    public abstract class BaseMe
    {
       public virtual void message1()
        {
            Console.WriteLine("BASE Message 1: " + this.GetType().ToString());
            Console.WriteLine("BASE Message 1: " + MethodBase.GetCurrentMethod().DeclaringType);
        }
        public virtual void message2()
        {
            Console.WriteLine("BASE Message 2: " + this.GetType().ToString());
            Console.WriteLine("BASE Message 2: " + MethodBase.GetCurrentMethod().DeclaringType);
        }
    }



Output



As can bee seen running the virtual method from the non-overridden abstract methods produces different results (message 1 if you are not keeping up).

this.GetType()

Returns the calling class TopClass.

MethodBase.GetCurrentMethod().DeclaringType

Returns the BASE method of the method that is run or Gets the class that declares the method, which has NOT be overridden.


Which is more usefully ?

BOTH ARE !!!!

It also all depends what you want to log, you could log both!




No comments:

Post a Comment

Comments are welcome, but are moderated and may take a wee while before shown.