What's the meaning of "apostrophe + number" in the object type of properties with generics (eg. "Collection`1")?
.net, c#, fully-qualified-naming, generics, reflection
Solution
The ``1` means a generic type, with 1 generic parameter.
One way of getting the string is by using the System.CodeDom, as suggested by @LukeH:
using System;
using System.CodeDom;
using System.Collections.Generic;
using Microsoft.CSharp;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
using (var p = new CSharpCodeProvider())
{
var r = new CodeTypeReference(typeof(Dictionary<string, int>));
Console.WriteLine(p.GetTypeOutput(r));
}
}
}
}
An alternative method is here. See below for @jaredpar's code:
public static string GetFriendlyTypeName(Type type) {
if (type.IsGenericParameter)
{
return type.Name;
}
if (!type.IsGenericType)
{
return type.FullName;
}
var builder = new System.Text.StringBuilder();
var name = type.Name;
var index = name.IndexOf("`");
builder.AppendFormat("{0}.{1}", type.Namespace, name.Substring(0, index));
builder.Append('<');
var first = true;
foreach (var arg in type.GetGenericArguments())
{
if (!first)
{
builder.Append(',');
}
builder.Append(GetFriendlyTypeName(arg));
first = false;
}
builder.Append('>');
return builder.ToString();
}
Problem
I have an object (`MyObject`) with a property (`MyProperty`). I want to get it's type name (i.e. `String` or `MyClass` etc.). I use: ``` PropertyInfo propInfo = typeof(MyObject).GetProperty("MyProperty"); Console.WriteLine(propInfo.PropertyType.Name); Console.WriteLine(propInfo.PropertyType.FullName); ``` No problem with simple types, but when `MyProperty` is a generic type, I face problems on getting it's name (e.g. `Collection<String>`). It prints: Collection`1 System.Collections.ObjectModel.Collection`1[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] What is that ``1`? And how can I obtain "`Collection<String>`"?