Is there any way for the nameof operator to access method parameters (outside of the same method)?
Asked Answered
N

1

40

Take the following class and method:

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

So getting "Create" is obvious: nameof(Foo.Create)

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

Nefen answered 20/5, 2016 at 15:2 Comment(4)
Just out of curiosity, why do you want that?Kunlun
@PauloMorgado i'm flowing json directly through my system with as minimal typing as possible. I like that in my tests i can easily signify the relationship between a property and it's json name.............................. $"{nameof(Person.Name)}:chris, foo:bar" (i'm in a comment box, this isn't a literal copy & paste but general idea). It's harder to express this relationship between a json property-name & value pair and the relationship to a method's argument's name & type pair. I'm tired of the never ending mapping layers when all i wanted was the direct input.Nefen
@PauloMorgado One very useful case would be IoC container Bootstrapping, like Ninject's WithConstructorArgument taking a reflected string literal parameter name - any change to the method signature, and boom! the bootstrapping breaks. It would have been ideal to have used nameof(Class.Method.Parameter) instead.Wien
This is an issue on C# github, those who feel strongly enough about it can upvote it so that it gets implemented in the future versions of C#Knut
R
36

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)
                     .GetMethod(nameof(Program.Main)).GetParameters()
                     .Select(p => p.Name);
Requiescat answered 20/5, 2016 at 15:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.