Home > OS >  .net 6 The type of namespace could not be found
.net 6 The type of namespace could not be found

Time:07-07

I created a program with .net 6. When I create add a class and then instantiate it in the main. I get the error

Error CS0246 The type or namespace name 'AbilityScoreCalculator' could not be found (are you missing a using directive or an assembly reference?)

The Class Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ability_Score_Calculator
{
    internal class AbilityScoreCalculator
    {
        // ...
        public void CalculateAbilityScore()
        {
           // ..
        }

    }
}

The Main Method Code

AbilityScoreCalculator calculator = new AbilityScoreCalculator();

However when I do the same in .net 5 all is well as shown below

Class code as above

Main Method Code

using System;

namespace Ability_Score_Calculator
{
    internal class Program
    {
        static void Main(string[] args)
        {
            AbilityScoreCalculator calculator = new AbilityScoreCalculator();
            
        }
    }
}

CodePudding user response:

I'm going to assume that your .Net 6 "Main Method Code" is using Top Level Statements, where

AbilityScoreCalculator calculator = new AbilityScoreCalculator();

Is the entire contents of the Program.cs file. No explicit class, no curly braces, nothing else.

When you use Top Level Statements, the code in that file doesn't belong to any namespace (this might not be technically true, but practically good enough). Because of that, the compiler is correct that it doesn't know about the AbilityScoreCalculator type. You need to bring it into scope with a using statement.

// this is the ENTIRE contents of the Program.cs file

using Ability_Score_Calculator;
AbilityScoreCalculator calculator = new AbilityScoreCalculator();
  •  Tags:  
  • c#
  • Related