1

I'm wondering why I don't have to use required namespaces anymore in a .NET 7.0 application. I'm doing some tests in Blazor app and I noticed that I no longer have to include namespaces at the beginning of the file like I used to.

In that example file that I'm showing I'm using IEnumerable interface and HttpClient class. Why I don't have to use below at the beginning of the file ?

using System.Collections.Generic;
using System.Net.Http; 

If I include those anyway, then the IDE shows them as unnecessary namespaces that I can get rid - why? Where does C# know which namespace these interfaces/class needs?

I'm not aware of any file that would globally use these namespaces. Is there anything like that ?

The project is Blazor Server App. I'm using .NET 7.0, Visual Studio 2022 Version 17.6.4

enter image description here

Md Farid Uddin Kiron
  • 16,817
  • 3
  • 17
  • 43
Dear Deer
  • 515
  • 1
  • 11
  • 29

1 Answers1

3

If I include those anyway, then the IDE shows them as unnecessary namespaces that I can get rid - why? Where does C# know which namespace these interfaces/class needs?

Well, It calls implicit using directives, which means that you can use types defined in these namespaces without having to specify their fully qualified name or manually add a using directive.

Most importnatly, may or may not know since .NET 6 or C# 10 it has been introduced, When the feature is enabled, the .NET SDK adds global using directives for a set of default namespaces based on the type of project SDK.

Default Project configuration .NET6 and higher:

If you check the default configuration in .csproj file you can get the details as following:

enter image description here

Note: This features for new C# projects that target .NET 6 or later have ImplicitUsings set to enable by default.

If you would like to enable or disable this feature, you can do that as following:

<PropertyGroup>
  <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

Note: If you wan to remove this property you can set it to false or disable. In addition, please refer to this official document for more details.

Md Farid Uddin Kiron
  • 16,817
  • 3
  • 17
  • 43