It is easy to declare a method, which takes a method name as a string:
public void DoSomethingWithMethodName(string methodName)
{
// Do something with the method name here.
}
and the call it as:
DoSomethingWithMethodName(nameof(SomeClass.SomeMethod));
I want to get rid of nameof
and call some other method as:
DoSomethingWithMethod(SomeClass.SomeMethod);
and then be able to get the name of the method the same as in the example above. It "feels" possible to do that using some Expression
and / or Func
sorcery. The question is what signature this DoSomethingWithMethod
should have and what it should actually do!
====================================
The question seems to cause a lot of confusion and the answers assume what I did not ask. Here is a hint at what I am aiming but cant' get right. This is for some different problem (for which I have a solution). I can declare:
private async Task CheckDictionary(Expression<Func<LookupDictionary>> property, int? expectedIndex = null)
{
await RunTest(async wb =>
{
var isFirst = true;
foreach (var variable in property.Compile().Invoke())
{
// Pass the override value for the first index.
await CheckSetLookupIndex(wb, GetPathOfProperty(property), variable, isFirst ? expectedIndex : null);
isFirst = false;
}
});
}
where GetPathOfProperty
comes from:
https://www.automatetheplanet.com/get-property-names-using-lambda-expressions/
and Fully-qualified property name
and then use:
[Fact]
public async Task CommercialExcelRaterService_ShouldNotThrowOnNumberOfStories() =>
await CheckDictionary(() => EqNumberOfStories, 2);
where EqNumberOfStories
is:
public static LookupDictionary EqNumberOfStories { get; } = new LookupDictionary(new Dictionary<int, string>
{
{ 1, "" },
{ 2, "1 to 8" },
{ 3, "9 to 20" },
{ 4, "Over 20" }
});
As you can see, I am passing a property and then "unwinding" it to get to the source. I'd like to do the same but in a simpler setup as described above.