Chris Marisic Chris Marisic - 1 year ago 71
C# Question

Is there any way for the nameof operator to access method parameters?

Take the following class and method:

public class Foo
public Foo Create(string bar) {
return new Foo(bar);

So getting "Create" is obvious:

Is there any way to get "bar" other than using reflection to read the parameters at run time?

Answer Source

No. There is no way to get the parameter names from the outside of the method using nameof. nameof doesn't work for method parameters if you want the name on the calling side (for the callee it does work obviously). The other methods you mentioned, like reflection, do work.

var parameterNames = typeof(Program)
                     .Select(p => p.Name);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download