Search code examples
c#directiveusing

What does the statement "to qualify the use of a type in that namespace" mean in C#


I am a beginner in C# and came across the below error when using the Console.WriteLine function.

The name 'Console' does not exist in the current context

My understanding of the using keyword is that it acts like a require or import in JavaScript.

So I then added the statement using System; at the top on the namespace file since a suggestion from the IDE gave me something like System.Console. Now I do not have the error anymore.

Out of curiosity I went to the C# docs in the using Directive section. And there is the following state:

The using directive has three uses:

To allow the use of types in a namespace so that you do not have to qualify the use of a type in that namespace:

What does the part - so that you do not have to qualify the use of a type in that namespace: mean.

And why the using keyword is called a directive or what is a directive in general programming in contrast to the directives I use for example in Angular?

Thanks.


Solution

  • What does the part - so that you do not have to qualify the use of a type in that namespace: mean.

    C# distinguishes between simple names, which have a name and an optional type argument, like String or List<int>, and qualified names which have multiple names separated by dots, like System.String or System.Collections.Generic.List<int>.

    When you have a using directive, you can elide the used qualifier.

    And why the using keyword is called a directive or what is a directive in general programming

    In C# we have declarations like namespace Foo or class Bar or void M() {} We have statements, like foreach(var foo in bar) blah(); What then is using System; ? It's not a declaration; no new item is declared. It's not a statement -- statements are control flow elements, but the using directive introduces no control flow. It directs the compiler to have a particular rule for resolving names, and so it is a directive.

    All of this information is in the C# specification. I strongly recommend that you get yourself a copy of the spec and consult it when you have questions like these. That will be faster and easier for you than posting a question here.