Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 470
Chris Marisic Avatar asked May 20 '16 15:05

Chris Marisic


Video Answer


1 Answers

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); 
like image 127
Patrick Hofman Avatar answered Sep 19 '22 07:09

Patrick Hofman