views:

75

answers:

2

I can't remember exactly where I've seen this strange '1 (single-tick and the number 1) appearing next to classnames, but it's shown up when inspecting variable values while debugging and most recently in the answer to this question.

targetClass.BaseTypes.Add(new CodeTypeReference { BaseType = "DataObjectBase`1[Refund]", Options = CodeTypeReferenceOptions.GenericTypeParameter })

I'm curious: where does this come from and why is it there?

+4  A: 

It's a generic type with 1 type parameter.

For example, List<T> is

System.Collections.Generic.List`1

and Dictionary<TKey, TValue> is

System.Collections.Generic.Dictionary`2

This allows generic types to be overloaded by the number of type parameters.

Mehrdad Afshari
+1 Yikes! 6 seconds faster - that is the closest I have ever seen two answers together! Well played...
Andrew Hare
@Andrew: I was beat by Jon by 3 seconds, I think.
Mehrdad Afshari
Leave it to Jon to hold the record :)
Andrew Hare
So it was just decided upon as convention? Strange that you can use a ♠ character in a classname, but not the lowly, common, single-tick
Chris McCall
Oh, and I think you owe Andrew a Coke ;)
Chris McCall
@Chris: Yes, the C# compiler uses this convention to generate generic type names. In the C# spec "section 2.4.2 Identifiers," the valid character classes that can be used for identifiers are specified. Backtick is not one of them.
Mehrdad Afshari
@Chris: Sure! If I ever see him in person ;)
Mehrdad Afshari
+2  A: 

It's the number of generic type parameters in CLS-compliant class names. It is needed because types can be overloaded on number of parameters; e.g.:

class Foo { }
class Foo<T1> { }
class Foo<T1, T2> { }

To distinguish these cases, compiler generates the following distinct names:

Foo
Foo`1
Foo`2

Note that while this is a CLS provider requirement, it is not a CLR requirement or limitation. As far as CLR itself is concerned, a generic type can have any name, but no two types can have the same fully qualified name. Hence the need for the backtick mangling scheme.

Pavel Minaev