0

I need to write a method that takes both the name and the type of a passed argument. For example, a call might look like this:

MyMethod( nameof(MyVar), MyVar.GetType() );

Is there any way to simplify this call so that I pass only one argument instead of two, but the method can still figure out both the name and type of that passed argument? The only way I know is by creating a macro and running the source through a pre-build external C# preprocessor. Then the call could look something like:

MyMethod( MyVar );

...but I want to avoid using a preprocessor.

Digiproc
  • 215
  • 1
  • 9
  • Depending on what you want, the marked duplicate may address your need. But note that _in general_ it makes zero sense to ask what the _name_ of the argument that was passed to the method is, because **there's no guarantee the value passed even has a name** (unless of course the argument is passed by reference, a tiny corner-case exception). But, if you can constrain the problem so that an `Expression`-based approach works in your case, you can fake it, getting the name and type from the `Expression` value. – Peter Duniho Jun 23 '19 at 04:36
  • Yep, that answered it. Specifically, the blog post referenced by Rinat Abdullin uses an Expression object (all you have to do is pass a '() => MyVar' as the argument), and from that you can find out anything (name, type, value, etc.). Thanks! – Digiproc Jun 23 '19 at 09:52

0 Answers0