-1

I'm working on code generation and during this task I need to create the C# representation of the typename that may contain type parameters.

E.g. I need to get "Dictionary<int, string>" from "Dictionary`2[[int], [string]]".

In the generic case this should be a lot more complex than just string replace.

Update to answer comments in questions

  • I'm generating source code,
  • my input is either a Type.Fullname as string or a Type object (as these can be easily converted to each other).
  • While not typical, my code should be prepared for nested type parameters.
White hawk
  • 1,468
  • 1
  • 15
  • 23
  • [This](http://stackoverflow.com/questions/721870/how-can-i-get-generic-type-from-string-representation) question is similar, but it refers to the opposite direction, and had no answers that could help here and don't just replace strings. – White hawk Nov 02 '15 at 14:41
  • what did you try so far? It seems to be Typename`nrOfParameters[[par1],[par2]....] – Icepickle Nov 02 '15 at 14:41
  • Are you just generating text source code, or are you actually using the type builder system to build types? – Ron Beyer Nov 02 '15 at 14:42
  • I am sure this question has been asked before but I cannot easily find the link. Is your input a Type object or a string in the format you indicated? If it is a string then your first task is to write a lexer and parser for that language. Have you done so? – Eric Lippert Nov 02 '15 at 14:42
  • @DStanley: How does your proposed algorithm work on a dictionary mapping integers onto lists of strings? – Eric Lippert Nov 02 '15 at 14:43
  • @EricLippert That's why I deleted it. Immediately thought of several cases where it failed :) – D Stanley Nov 02 '15 at 15:15

1 Answers1

1
public string ToCSharpType(Type type)
{
    if (!type.IsGeneric)
        return type.FullName;

    var result = new StringBuilder();
    string name = type.GetGenericTypeDefinition().FullName;
    result.Append(name.Substring(0, name.IndexOf('`'));
    result.Append('<');
    var args = type.GetGenericArguments();
    for (int i = 0; i < args.Length; i++)
    {
         result.Append(ToCSharpType(args[i]);
         if (i < args.Length - 1)
             result.Append(", ");
    }
    result.Append('>');
}
György Kőszeg
  • 17,093
  • 6
  • 37
  • 65