-3

I'm using the nameof operator in C# quite often. So I'm wondering, is there a way to create a shorter version (a wrapper or an alias) for this operator, like _(Identifier) instead of nameof(Idenfier). More details: I need to create long array of string like var columns = new[] { nameof(Property1}, nameof(Property2), ... }. I'd like to make the code a bit shorter like var columns = new[] { _(Property1), _(Property2) ...}. Is there a feature in C# to make this posible?

stuartd
  • 70,509
  • 14
  • 132
  • 163
Kenna
  • 15
  • 3
  • Static read-only string FTW... – Jim G. Jan 17 '23 at 03:00
  • Maybe you can achieve desired result with code generation or runtime reflection? – Serg Jan 17 '23 at 03:03
  • 4
    Are you trying to make the code itself shorter or are you trying to type less? If the latter then you should be aware that VS allows you to type the same text on multiple lines at the same time. If you hold the *Alt* key down while dragging the mouse, you can select an arbitrary block of text. You can select a block with zero width and multiple lines in height, then type `nameof()` once and that will appear on every line. You can then just type in the property names one by one. That trick with the *Alt* key is how you should select code in VS to copy here, so you can trim leading whitespace. – jmcilhinney Jan 17 '23 at 03:06
  • You could use [NimbleText](https://nimbletext.com/) to generate them. Make a list of properties, write a little template to generate the `nameof` clauses, then paste that in – stuartd Jan 17 '23 at 03:09

1 Answers1

1

you CANT do that!

even if you could, with something like this:

private static string N(Expression<Func<object>> expr) => ((MemberExpression)expr.Body).Member.Name;

it wouldn't really be efficient considering it's usage:

var name = N(() => myVariable);

and also anything like this would be slow,

because once you compile your code with nameof() it will put your name like a normal string, consider this example:

var myname = "awdawda";
1.Console.WriteLine(nameof(myname));
2.Console.WriteLine(N(() => myname));

for line 1, generated IL is this:

    IL_0012: ldstr        "myname"
    IL_0017: call         void [System.Console]System.Console::WriteLine(string)
    IL_001c: nop

just a normal string at compile time,but if you look at line 2 you'll see this:

enter image description here

can you see the mess it just create for a single name ?

with all been said, I suggest you keep working with nameof(), or create some sort of source generator to make the work for you , that would be even harder to achieve.

AliSalehi
  • 159
  • 1
  • 1
  • 13
  • Thank you! I've tried this before posting the question. I know that drawback. It does not suite my need. I think a code snippet may be better to quickly input. – Kenna Jan 17 '23 at 04:15