2

I saw a library code variable named like this

  private readonly Encoder <Encoder>k__BackingField;

I tried to name it in Visual Studio 2022 but it didn't work

Can c# name add angle brackets? Which version of grammar is it?

  • 1
    `private readonly Encoder k__BackingField` you maybe mistyped a space.. Look for more information about [Generics](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/types/generics) – Jeroen van Langen Jul 07 '23 at 11:19
  • 8
    Was that actual writtensource code you looked at? Because that looks like a compiler generated backing field that you mostly see after decompiling an assembly. – Karl-Johan Sjögren Jul 07 '23 at 11:22
  • 4
    "Decompiled" IL can look a little strange when converted to C# as there are all sorts of things that are valid IL but invalid C#. – phuzi Jul 07 '23 at 11:22
  • 2
    @JeroenvanLangen I bet that it is not about generics but about compiler generated field names which OP sees with some kind of decompilation tool. – Guru Stron Jul 07 '23 at 11:25

1 Answers1

-1

The angle brackets (< and >) are used for generic type parameters, and they are not allowed in variable names.

Examples that work are:

private readonly Encoder<T> tEncoder;

private readonly Encoder<string> stringEncoder;

...

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Saiko
  • 102
  • 6
  • 4
    Not in C#, but they *are* allowed in IL, which is why the C# compiler uses them when it needs to synthesize fields, e.g. based on local variables. I think that's much more likely than that this was a deliberate attempt to use generics, especially given the rest of the name. – Jon Skeet Jul 07 '23 at 11:23