Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ToString() on generic types have square brackets?

Tags:

c#

generics

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?

like image 230
David Klempfner Avatar asked Oct 13 '16 11:10

David Klempfner


1 Answers

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.
like image 62
Lucas Trzesniewski Avatar answered Nov 09 '22 00:11

Lucas Trzesniewski