19

Why does new List<string>().ToString(); return the following:?

System.Collections.Generic.List`1[System.String]

Why wouldn't it just bring back System.Collections.Generic.List<System.String>. What's with the strange non C# syntax?

David Klempfner
  • 8,700
  • 20
  • 73
  • 153
  • 3
    Just in case yo would like to get name with <> brackets http://stackoverflow.com/a/14284719/797249 – Artiom Oct 13 '16 at 11:13
  • To the person who voted to close this because it's opinion based. How is it opinion based? The answer provided is completely objective. – David Klempfner Jul 03 '17 at 04:30

1 Answers1

18

Because <> brackets is C# syntax. The System.Object.ToString() implementation returns the type name with the CLR syntax.

Consider this:

System.Collections.Generic.List<System.String>

Looks nice when you're developing in C#, but say you call ToString from C++/CLI. Would you expect the following instead?

System::Collections::Generic::List<System::String>

Obviously, the behavior shouldn't change based on which language the caller was compiled in, so the returned string is language-neutral.


This MSDN page lists the type name conventions used by the CLR. (Thanks to Matthew Watson for the link).

As for the arity (the `1 part), you can find more info in ECMA-335 (the CLI specification):

I.10.7.2 Type names and arity encoding

CLS-compliant generic type names are encoded using the format name[`arity] , where [...] indicates that the grave accent character ` and arity together are optional. The encoded name shall follow these rules:

  1. name shall be an ID (see Partition II) that does not contain the ` character.
  2. arity is specified as an unsigned decimal number without leading zeros or spaces.
  3. For a normal generic type, arity is the number of type parameters declared on the type.
  4. For a nested generic type, arity is the number of newly introduced type parameters.
Community
  • 1
  • 1
Lucas Trzesniewski
  • 50,214
  • 11
  • 107
  • 158