Get Current Method Name in CF 2.0?

Hi!

Does anyone knows a way the get the name of the current method in CF 2.0
At the .Net Framework it works this way:
System.Reflection.MethodBase.GetCurrentMethod().Name


Thanks in advanvce...
Markus


Answer this question

Get Current Method Name in CF 2.0?

  • ThomasB.

    GetCurrentMethod() is not supported on CF in v1.0 or v2.0. To do this right we would need to have some mechanism to ensure the caller never gets inlined ... which we dont as of yet.

    There is another way that I would NOT recommend, because of perf and unreliability. You should NOT use this in production code.

    You would essentially catch an exception you throw and get the stack trace and parse out the method name from your stack trace. This is very error prone since changing the stacktrace format will break you.

    using System;

    public class MyClass

    {

       public static int Main()

       {

       Foo();

       return 0;

    }

    public static void Foo()

    {

       Console.WriteLine("I am in Foo().");

       FooBar();

    }

    public static void FooBar()

    {

       string MethodName = "";

       Console.WriteLine("I am in FooBar().");

       try

       {

          throw (new ArgumentException());

       }

       catch (ArgumentException aex)

       {

          Console.WriteLine(aex.StackTrace);

          MethodName = ParseOutMethodName(aex.StackTrace);

       }

       Console.WriteLine("Name = {0}", MethodName);

    }

    public static string ParseOutMethodName(string input)

    {

       string[] temp = input.Split(new char[] { '\n' });

       string[] temp2 = temp[0].Split(new char[] { '.', ' '});

       return temp2[temp2.Length - 1];

    }

    }



  • tdickson

    Hi,

    I am trying to use your code, but it seems that aex.StackTrace doen't exist in Compact Framework 1.0.
    Any other way to resolve the problem
    Thx,
    Moiss


  • Claudio Lassala MVP

    Yes, that's right, the StackTrace has been added to the CF 2.0.
  • Get Current Method Name in CF 2.0?