locked
Reflection code: C# and VB.Net equivalents in .NET 1.1 RRS feed

  • Question

  • Hi
    I used "System.Reflection.MethodBase.GetCurrentMethod().DeclaringType" in VB.NET to get the type of current class. But, if I try to use the same code in C#, it gives "class was expected" error and does not compile.

    What is the equivalent of "System.Reflection.MethodBase.GetCurrentMethod().DeclaringType" in C#?

    Please advice. Thanks

    Pankaj

    Friday, December 16, 2005 5:58 PM

Answers

  • Actually, GetType() is an instance method on System.Object. So for any instance, obj, you can call obj.GetType() to find the class object (i.e. Type).
     
    You cannot call typeof on an object. You use typeof in C# on type names to retrieve the class object. For instance:
     
    Type t = typeof(MyClass);
    Monday, December 19, 2005 6:21 PM

All replies

  • The same code will work in C# as it is a static class however there is an easier way.  GetType() will give you the type of the current class instance.

    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType == GetType()

    To get the type of any object in C# you can use typeof(object).

    Michael Taylor - 12/16/05

    Friday, December 16, 2005 6:53 PM
  • Thanks Michael. It works now.

    private static Type thisClassType = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType;

    private static readonly ILog logger = LogManager.GetLogger(thisClassType);

    Friday, December 16, 2005 8:21 PM
  • Actually, GetType() is an instance method on System.Object. So for any instance, obj, you can call obj.GetType() to find the class object (i.e. Type).
     
    You cannot call typeof on an object. You use typeof in C# on type names to retrieve the class object. For instance:
     
    Type t = typeof(MyClass);
    Monday, December 19, 2005 6:21 PM