Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse Type returned value to generate new source code

Tags:

c#

.net-2.0

I have this problem:

I want to generate a new source code file from a object information.

I make something like this:

dictParamMapping is a Dictionary<string, Type> where the string is a variable name and Type is the type of that variable.

I get the type to build new code using:

dictParamMapping[pairProcess.Value].Type.Name (or FullName)

When Type is int, string, datatable etc... everything works fine but when it is a dictionary, list or any other like that it returns something like:

System.Collections.Generic.Dictionary`2[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Double, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]

Which is not correct to build that new source code. I would like to get something like Dictionary<int, double>

Can any one help me?

like image 666
pasapepe Avatar asked Jul 02 '12 13:07

pasapepe


1 Answers

You appear to want to get a C#-compatible name from a System.Type. You can do this with the CSharpCodeProvider class.

var typeReference = new CodeTypeReference(typeof(Dictionary<int, double>));

using (var provider = new CSharpCodeProvider())
    Console.WriteLine(provider.GetTypeOutput(typeReference));

Output:

System.Collections.Generic.Dictionary<int, double>

Note that this is not guaranteed to always provide you with a valid type-name. In particular, compiler-generated types (such as for closures) will typically have type-names that are invalid in C#.

like image 123
Ani Avatar answered Sep 20 '22 21:09

Ani