C# System Namespace - why do I need to import it?

Viewed 1210

In C# if I use a type alias like string instead of (System.String) then I do not need to add a using System; directive - it compiles just fine.

However, if I change the type from the alias to the aliased Type explicitly - System.String - then it will not compile without the using directive. This seems to be true of all primitive Types (int/Int32, bool/Boolean) etc.

Why does the compiler import System for me when using an alias but not when using the actual type name?

3 Answers

The aliases are more "as if" at the top of every file, the compiler was inserting

using string = System.String;
using int = System.Int32;
using decimal = System.Decimal;

Etc.

I don't believe that's how the compiler actually implements1 the built-in aliases, but that's the overall effect. When you use using alias directives, you don't also need to have a using directive for their enclosing namespace, and it doesn't have the effect of also pulling it's enclosing namespace into scope.


1My search-foo in the Roslyn github repository is letting me down.

There is practically no difference between both string and System.String but still String the C# keyword string maps to the .NET type System.String - it is an alias that keeps to the naming conventions of the language.

Also string is a keyword (an alias in this case) whereas String is a type.

Note : If you use Visual Studio 2015 or + and try to use String the program suggests you to "simplify your code", carrying it to string

So you can avoid the System.String and go with string no problems.

enter image description here

You only need to import the namespace if you are not using the full, qualified name of the type:

namespace Test {
  class Cxx {
     public System.String _exampleField; 
  }
}

vs:

using System;

namespace Test {
  class Cxx {
     public String _exampleField; 
  }
}

You can import a single type from a namespace using an alias.

The built-in aliases work in a similar way to the ones you write; if instead of the built-in alias string you had your own, they you would not need to import the whole System namespace:

using mystring = System.String;

namespace Test {
  class Cxx {
     public mystring _exampleField; 
  }
}

If the only types from the System namespace you use are the ones which have aliases, you don't need the import.

namespace Test {
  class Cxx {
     public string _exampleField; 
  }
}
Related