5

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?

Dieter Meemken
  • 1,937
  • 2
  • 17
  • 22
  • 4
    It is because `string` is an alias for the `System.String` class which is sitting in the `System` namespace. If you use `typeof(string).Name` you get only the classname `String`. – Tim Schmelter Dec 09 '15 at 10:32
  • 1
    In addition to _Tim Schmelter_'s comment above: The same can be said for the primitives: `typeof(int).FullName` will return `int`, but `typeof(Int32).FullName` will return `System.Int32`. System.`String` and `string` are exactly the same, and are used based on preference. I personally use `string` for fields, and `String` for static methods/constants, like `String.Empty` or `String.Format(...)`. I always thought they were EXACTLY the same in everything, but apparently their type-FullName are also different. So thanks for this question, because now I've also learned something new. :) – Kevin Cruijssen Dec 09 '15 at 10:59

2 Answers2

11

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.

Community
  • 1
  • 1
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
1

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)

Community
  • 1
  • 1
Lukas Boersma
  • 1,022
  • 8
  • 26
  • Thanks for the hint, but is the creation of an CSharpCodeProvider not 'to expensive' for this, specially if you do it often? – Dieter Meemken Dec 09 '15 at 10:50
  • I did not measure it, but if you need to do this very often, I would suggest to cache the c# names in a `Dictionary` or something like that. If you need the name, look it up in the dictionary. If it is not in it, perform the slow `GetTypeOutput` and save it in the dictionary. – Lukas Boersma Dec 09 '15 at 10:52
  • 1
    10.000 tries took 11ms on my end. So performance is not an issue. – Patrick Hofman Dec 09 '15 at 10:53