If I use typeof(int).Name
, I get "Int32".
Is there a way to get "int" directly from the system, without me doing any string operations on the "Int32"?
Asked
Active
Viewed 726 times
0

bla
- 301
- 2
- 11
-
Can you add a dictionary that maps from `Type` to `string` and look up with it? – Sean Mar 26 '20 at 10:47
-
I was hoping to get it from an already existing dictionary listing some available types. :) – bla Mar 26 '20 at 10:52
-
1See the discussion in [this answer and its comments](https://stackoverflow.com/a/2579755/5133585). Getting a "C# native way" of writing the type name isn't particularly useful. Why are you trying to do this? – Sweeper Mar 26 '20 at 10:52
-
1`int` is a C#-ism, there is nothing in the runtime that knows about his language-specific name (as well there shouldn't be, popular as it is, C# isn't the only .NET language). You can write a simple lookup table for all the types C# has dedicated names for; it's a fixed list. Conceivably you could also rely on Roslyn (somehow) but that seems massive overkill. – Jeroen Mostert Mar 26 '20 at 10:53
-
1Does this answer your question? [Is there a way to get a type's alias through reflection?](https://stackoverflow.com/questions/1362884/is-there-a-way-to-get-a-types-alias-through-reflection) The exact duplicate – Pavel Anikhouski Mar 26 '20 at 11:00
-
1@PavelAnikhouski ah yes, this is actually exactly the same case, didn't see it in the recommendations though. I will mark it as a duplicate. Thanks. :) – bla Mar 26 '20 at 11:03
1 Answers
1
I use a dictionary for this. Most probably got it from another StackOverflow answer a few years ago, but can't find it at the moment...
private static readonly Dictionary<Type, string> Aliases =
new Dictionary<Type, string>()
{
{ typeof(byte), "byte" },
{ typeof(sbyte), "sbyte" },
{ typeof(short), "short" },
{ typeof(ushort), "ushort" },
{ typeof(int), "int" },
{ typeof(uint), "uint" },
{ typeof(long), "long" },
{ typeof(ulong), "ulong" },
{ typeof(float), "float" },
{ typeof(double), "double" },
{ typeof(decimal), "decimal" },
{ typeof(object), "object" },
{ typeof(bool), "bool" },
{ typeof(char), "char" },
{ typeof(string), "string" },
{ typeof(void), "void" }
};

Fortega
- 19,463
- 14
- 75
- 113
-
`string result = Aliases.TryGetValue(typeOfInterest, out string value) ? value : typeOfInterest.Name;` – Dmitry Bychenko Mar 26 '20 at 10:57
-
2I guess it was this [answer](https://stackoverflow.com/a/1362899/4728685), looks like an exact duplicate – Pavel Anikhouski Mar 26 '20 at 11:01