10

I was learning MVC WebAPI and I was following a tutorial and everything was going fine untill I saw the following:

namespace HelloWebAPI.Controllers
{
    using System;
    
    public class ProductsController : ApiController
    {
        
    }
}

What we usually do is that we add the resources\scope in the beginning like this:

using System;

namespace HelloWebAPI.Controllers
{
    public class ProductsController : ApiController
    {
        
    }
}

I want to have a better understanding about it

Thanks.

spaleet
  • 838
  • 2
  • 10
  • 23
Moon
  • 19,518
  • 56
  • 138
  • 200

3 Answers3

14

There is a difference, small but there is.

It's all about the sequence of name resolution made by compiler. The good answer on subject you can find here:

Should Usings be inside or outside the namespace

In practise in first case compiler, in case could not find a type information immediately, would search among namespaces declared inside using. In second case, instead, would search first among the actual namespace and after only go to search inside declared outside.

Community
  • 1
  • 1
Tigran
  • 61,654
  • 8
  • 86
  • 123
7

You can define more than one namespace in a C# file.

Putting using statements inside of a namespace means they are only in use within that namespace for that file.

Putting them outside of the namespace means they apply for all namespaces within the file.

It's kind of how the scope of variable names applies only in the most inner braces that contains them and deeper.

Patashu
  • 21,443
  • 3
  • 45
  • 53
-3

The only difference is with scope of using statements. If you use using inside a namespace then these using statements will be included in all files which place under that namespace. And if you use using statements outside namespace then these using statements will be valid only for current file.

File 1:

namespace MyNamespace
{
    using System;
    using System.IO;

    public MyClass
    {
    }
}

File 2:

namespace MyNamespace
{
    public MyClassV2
    {
    }
}

In this example you don't need to add using in File 2 for MyClassV2 as MyNamespace already has these using statements. But for a different namespace you need to add using statements.

fhnaseer
  • 7,159
  • 16
  • 60
  • 112