Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why 'typeof(string).FullName' is giving 'System.String' and not 'string'?

Tags:

c#

types

typeof

Why typeof(string).FullName is giving System.String and not string? The same is with all other "simple" types like int, float, double, ...

I understand that typeof is returning the System.Type object for the given type, but why is string not also be an System.Type object ?

Is it because string is part of the c# language, and System.Typeis part of the system libraries?

like image 976
Dieter Meemken Avatar asked Dec 09 '15 10:12

Dieter Meemken


2 Answers

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

like image 106
Patrick Hofman Avatar answered Nov 15 '22 03:11

Patrick Hofman


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

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

If you need to get the shorter C# alias name of a 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)

like image 45
Lukas Boersma Avatar answered Nov 15 '22 04:11

Lukas Boersma