Why does 'typeof (string) .FullName' give 'System.String' and not 'string'?

Why typeof(string).FullName gives System.String and not string ? Same thing with all the other "simple" types like int , float , double , ...

I understand that typeof returns a System.Type object for this type, but why is string also not a System.Type object?

Is it because string is part of C # and System.Type is part of system libraries?

+5
source share
2 answers

Because string is an alias for System.String . Your C # string code is converted at compile time to System.String . This is the same for other aliases .

+11
source

In C #, string is just an alias for System.String , so both are the same, and typeof returns an object of the same type.

The same applies to all other primitive types. For example, int is just an alias for System.Int32 .

If you need to get a shorter C # alias name of type, you can use CSharpCodeProvider.GetTypeOutput() instead of FullName :

 using Microsoft.CSharp; [...] var compiler = new CSharpCodeProvider(); var type = new CodeTypeReference(typeof(Int32)); Console.WriteLine(compiler.GetTypeOutput(type)); // Prints int 

(code snippet taken from this question )

+1
source

Source: https://habr.com/ru/post/1237743/


All Articles