raf
raf

Reputation: 11

Why does VS-Intellisense sometimes "use" the namespace and prepend it to a type in C#

Why does VS-intellisense sometimes write using at the top of the page and sometimes adds it inline like new namespace.class in C#?

For example

using Namespace;
Obj obj = new Obj();

and

obj = new Namespace.Obj();

Upvotes: 0

Views: 96

Answers (2)

Ortund
Ortund

Reputation: 8245

Visual Studio 2015 has a bug where it does this.

Whether or not you include a using statement at the top of your code file, the bug causes it to add the namespace in front of your definition.

I asked a similar question a few weeks ago and, on the recommendation of another user, submitted an issue on the relevant github project.

My issue was closed almost immediately with a rather snippy comment which basically said "update to Visual Studio 2017 because we fixed it in that version".

Upvotes: 1

Ahmad ElMadi
Ahmad ElMadi

Reputation: 2617

Sometimes two namespaces have the same class. So to avoid ambiguity the namespace is added to the class .

Example: Imagine that you have Namespace1 and Namespace2 and both of them has the class Employee

using Namespace1;
using Namespace2;

namespace MyNamespace
{
  public class MyClass
  {
    private Employee emp1; // does it come from Namespace1 or Namespace2 ? 
  }
}

So two solutions can be done in this case

one is to have the name space explecitly defined

using Namespace1;
using Namespace2;

namespace MyNamespace
{
  public class MyClass
  {
    private Namespace1.Employee emp1; 
  }
}

and the other is that you define from the beginning that you are using the Employee from a certain namespace as follows.

using Namespace1;
using Namespace2;
using Employee = Namespace1.Employee; 

namespace MyNamespace
{
  public class MyClass
  {
    private Employee emp1; //Notice the definition above
  }
}

Upvotes: 1

Related Questions