Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

reflection

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] 
like image 522
Jordan Avatar asked Dec 06 '10 18:12

Jordan


People also ask

What is a primitive type in C?

Data types are keywords that define the size and type of value that you can store in a variable. Primitive types are data types that come as part of the programming language. Non-primitive types are those defined by the programmer. They are also called reference types.

How can I get type by name?

To load a type by name, you either need it's full name (if the assembly has already been loaded into the appdomain) or its Assembly Qualified name. The full name is the type's name, including the namespace. You can get that by calling Type. GetType(typeof(System.

What do you mean by primitive data type?

What Does Primitive Data Type Mean? A primitive data type is either a data type that is built into a programming language, or one that could be characterized as a basic structure for building more sophisticated data types.


1 Answers

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.

like image 133
Jon Skeet Avatar answered Oct 05 '22 23:10

Jon Skeet