-1

I found a similar question here How can I find the method that called the current method? but answers in this question also give same result as I have mentioned in my first example

Here is method that I am using

public class iStore
    {
        public T GetSiteCacheValueByFunc<T>(Func<T> func) where T : class
        {
            var methodName = func.Method.Name;
        }
    }

Here I am using iStore.GetSiteCacheValueByFunc by using following code I get methodName <Index>b_2 while I should get GetAllLanguages

 public ActionResult Index()
    {
        var site = BusinessLogic.Caching.iStore;
        var languages = site.GetSiteCacheValueByFunc<IEnumerable<Language>>(() =>  LanguageManager.GetAllLanguages());
    }

If I use following code I get correct methodName GetAllLanguages but in this way I am not able to pass parameters to GetAllLanguages method

public ActionResult Index()
{
    var site = BusinessLogic.Caching.iStore;
    var languages = site.GetSiteCacheValueByFunc<IEnumerable<Language>>(LanguageManager.GetAllLanguages);
}

Where I am doing wrong? and how can I get correct methodName?

Community
  • 1
  • 1
Mujassir Nasir
  • 1,640
  • 4
  • 31
  • 52

1 Answers1

2

If you are using .NET 4.5 you can use an attribute : CallerMemberNameAttribute

public void MyMethod([CallerMemberName]string myCallerName = null)
{
  //use myCallerName
}
Alex Peta
  • 1,407
  • 1
  • 15
  • 26
  • Thanks, if you are handy with this would you please help me how to modify above code with this implementation? – Mujassir Nasir Sep 23 '14 at 11:43
  • I don't think this is useful here. `CallerMemberName` causes the compiler to insert the name of the function/property that calls `MyMethod`, not the name of the function that you're passing in. So in Mujassirs last example, you'd get "Index" instead of "GetAllLanguages". – Pieter Witvoet Sep 23 '14 at 11:51