Home > Back-end >  .net6 requiring fully qualified class name?
.net6 requiring fully qualified class name?

Time:07-31

I have a solution (ConsoleApp6) with program.cs and Dog.cs in Visual Studio In program.cs I am instantiating Dog.cs. I've been a .net programmer for years, but am on day one of switching to .NET 6 in program.cs "Dog" is not recognized (like it would have been in old .net) unless I qualify it with MyNameSpaceHere.Dog, even though it is the same exact namespace as program.cs.

ConsoleApp6.Dog dog = new ConsoleApp6.Dog(); //works

Dog dog = new Dog();  //does not

Error message says:Type or Namespace "Dog" could not be found. Even when I follow the fix and let VS create a new class Dog, it then doesn't recognize that. Clearly I'm making some newbie error here???

CodePudding user response:

What you are seeing is a consequence of the "top level statements" feature

Support was added so that you could "just code" without having to declare a namespace and a Program class with a Main method in it.

The consequence is that, everything that is in this "top level layer" is not part of any namespace, which means every reference to a class with a namespace will cause a full qualification if you don't include the using at the top of the file.

So the solution in your case is to just add the following at the top of your file:

using ConsoleApp6;

Dog dog = new Dog();  // works now

Note: this is a C#9 feature and not a .NET6 feature.

  • Related