Visual Studio 2022 file-scoped namespace issue

2.1k Views Asked by At

So I have VS 2022 and am trying to learn C#.

I am getting an error of Feature

'file-scoped namespace' is not available in C# 7.3 Please use language 10.0 or greater.

I found where one goes to Options>Code Style> Text Editor and change to File-scoped. Did that.

When I create my solution, I chose Blank Solution I then added an empty project using .NET framework 4.8 Next I added a code file Finally I add the following:

namespace Averages;

public static class TestClass
{
 
}

And I get the error. What in the world am I missing? I'm stumped. Edit: I just checked. I have .NET 7.0

2

There are 2 best solutions below

5
Leandro Bardelli On BEST ANSWER

You could solve this by:

namespace Averages 
{ 
   public static class TestClass
   {
 
   }
}

since Framework 4.8 doesn't allow File-scoped names, so the class should be "inside" the namespace.

But if you are learning, I would suggest don't use empty blank, syntax could be a bit different, but in learning mode this bit means a lot and you will found examples of code that often doesn't specify the syntax.

You could also try your code at Fiddle DOT NET https://dotnetfiddle.net/

0
AudioBubble On

The reason you can't use this syntax is because you created your project using .NET Framework 4.8. This is the old version of .NET, which only supports C# language version 7.3.

See the image below -- the top one is for the newest .NET versions (5.0+), the bottom one is for the old .NET Framework (4.x and below). This applies to class libraries too. enter image description here

File-scoped namespaces are a C#10 language feature, which are only available in .NET >= 6.0. That is why you can't use it in your .NET Framework 4.8 project.

You would need to create a project that supports the newer .NET versions, *not .NET Framework*, if you want to use the latest C# language features.

This Microsoft article describes the relationship between C#/.NET versions.