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 HelloWebAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
public class ProductsController : ApiController
{}
What we usually do is that we add the resources\scope in the beginning like this:
using HelloWebAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace HelloWebAPI.Controllers
{
public class ProductsController : ApiController
{}
My supervisor told me that it is okay and it is supposed to be okay, because it is an official MS tutorial on the subject.
** What I want to know that why this doesn't matter, so that I have a better understanding about it? **
As a rule, external using directives (System and Microsoft namespaces for example) should be placed outside the namespace directive. They are defaults that should be applied in all cases unless otherwise specified.
You can also create an alias for a namespace or a type with a using alias directive.
The using directive allows you to abbreviate a type name by omitting the namespace portion of the name—such that just the type name can be specified for any type within the stated namespace.
The namespace keyword is used to declare a scope that contains a set of related objects. You can use a namespace to organize code elements and to create globally unique types. namespace SampleNamespace; class AnotherSampleClass { public void AnotherSampleMethod() { System. Console.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With