Guillaume Slashy
Guillaume Slashy

Reputation: 3624

Convert CLR type names to equivalent idiomatic C# aliases (eg System.String => string, Int32 => int)

I am parsing some objects and I'd like to dynamically generate some code. The thing is that when I'm reading types I got things like :

System.String
System.Int32
Boolean

I know it's strictly identical for C# to string, int and bool. But when I'm parsing my object, i got the "System" versions and I want to dynamically generate some code using strings and I want to generate the alias description, can I do it easyly ? (without something like a Dictionary associating typeofs to strings...)

Upvotes: 3

Views: 1685

Answers (3)

JohnD
JohnD

Reputation: 14757

I don't know of a way to do this. However, there are not that many types so if it were me I would probably just write a mapping function.

You can find the list of C# type names here as a starting point:

http://msdn.microsoft.com/en-us/library/86792hfa(VS.71).aspx

Update: here is a reference for C# which includes decimal. Not sure why that was missing from above link: http://msdn.microsoft.com/en-us/library/ya5y69ds.aspx

Upvotes: 3

luqi
luqi

Reputation: 2909

string and int are aliases for System.String and System.Int32.

Seems like you can use this to get the Types from strings: http://msdn.microsoft.com/en-us/library/system.codedom.codetypeofexpression.aspx

// Creates a reference to the System.Int32 type.
CodeTypeReference int32typeRef = new CodeTypeReference("System.Int32");

But there is no way to get a string from type so you have to define your own mapping there: Is there a way to get a type's alias through reflection?

Upvotes: 1

samjudson
samjudson

Reputation: 56853

Once you compile the code you write in C# it no longer knows it came from C# code, therefore there is no way to automatically get the C# alias without doing exactly what you suggest - create a simple mapping dictionary.

The built in C# types are listed here: http://msdn.microsoft.com/en-US/library/ya5y69ds.aspx

This list is not going to change any time soon, as I shouldn't worry about hard coding this list into your application.

Upvotes: 1

Related Questions