Is it better to use the using within the namespace?

1

At work they suggested using the usings within the namespace.

namespace Functions.ProcessBatches.Transfers.Business
{
    using AutoMapper;
    using Microsoft.AspNet.Identity;
    using System.Security.Principal;

    public class Ejemplo{
    }
}

unlike:

using AutoMapper;
using Microsoft.AspNet.Identity;
using System.Security.Principal;

namespace Functions.ProcessBatches.Transfers.Business
{
    public class Ejemplo{
    }
}

I asked but they only told me that they are 'good practices' to enclose using in the namespace. Could someone give a more detailed explanation?

    
asked by Jesus Pocoata 06.04.2018 в 23:53
source

1 answer

1

In many cases it does not matter, but if you put your using within the namespace, the compiler will first look for those using.

Example ...

In a file you have this:

using System;
namespace Namespace1.SubNamespace
{
    public class Foo
    {
        private void Algo()
        {
            Console.WriteLine("");
        }
    }
}

And in another file you have this (you do not have any using):

namespace Namespace1
{
    public class Console
    {
    }
}

The compiler will search Namespace1 first before the System of the using, and will find Namespace1.Console and not System.Console. Obvious Namespace1.Console has no WriteLine method.

If you change the first file to:

namespace Namespace1.SubNamespace
{
    using System;
    public class Foo
    {
        private void Algo()
        {
            Console.WriteLine("");
        }
    }
}

The compiler will first find System.Console.

    
answered by 07.04.2018 / 00:28
source