How can I get the primitive name of a type in C#?

c#, reflection

Solution

EDIT: I was half wrong in the answer below.

Have a look at `CSharpCodeProvider.GetTypeOutput`. Sample code:

using Microsoft.CSharp;
using System;
using System.CodeDom;

class Test
{
    static void Main()
    {
        var compiler = new CSharpCodeProvider();
        // Just to prove a point...
        var type = new CodeTypeReference(typeof(Int32));
        Console.WriteLine(compiler.GetTypeOutput(type)); // Prints int
    }
}

However, this doesn't translate `Nullable<T>` into `T?` - and I can't find any options which would make it do so, although that doesn't mean such an option doesn't exist :)

There's nothing in the framework to support this - after all, they're C#-specific names.

(Note that `string` isn't a primitive type, by the way.)

You'll have to do it by spotting `Nullable`1` yourself (`Nullable.GetUnderlyingType` may be used for this, for example), and have a map from the full framework name to each alias.

Problem

I'm using reflection to print out a method signature, e.g. ``` foreach (var pi in mi.GetParameters()) { Console.WriteLine(pi.Name + ": " + pi.ParameterType.ToString()); } ``` This works pretty well, but it prints out the type of primitives as "System.String" instead of "string" and "System.Nullable`1[System.Int32]" instead of "int?". Is there a way to get the name of the parameter as it looks in code, e.g. ``` public Example(string p1, int? p2) ``` prints ``` p1: string p2: int? ``` instead of ``` p1: System.String p2: System.Nullable`1[System.Int32] ```

Original source

Related problems