Implicit Using in C#
Introduction
C# 10 introduced implicit usings, a feature designed to reduce boilerplate code by automatically including commonly used namespaces in your projects. This helps make your code cleaner and easier to manage. In this article, we'll explore what implicit usings are, how they work, how to manage them, and the benefits they offer.
Table of Contents
- What Are Implicit Usings
- How Implicit Usings Works
- Enabling Implicit Usings
- Adding Usings to Implicit Usings
What Are Implicit Usings
Implicit usings automatically include a predefined list of using
directives in your C# files, so you don't need to manually add them.
This feature is enabled by default in .NET 6 or later and varies depending on the project type.
For example, in a typical .NET console application, you might have several using
statements at the top of your files, like using System;
, using System.Collections.Generic;
, etc. With implicit usings, these are automatically included, allowing you to focus more on your code.
How Implicit Usings Works
When you create a new .NET project in .NET 6 or later, implicit usings are enabled by default. The specific namespaces included depend on the project type.
For Console Application
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
For ASP.NET Core Applications
/*In addition to all Console App usings*/
using System.Net.Http.Json;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
For Worker
/*In addition to all Console App usings*/
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
Enabling Implicit Usings
You can manage implicit usings through the .csproj
file. This allows you to enable, disable, or customize the list of implicit usings according to your project's needs.
PS.: Implicit usings are enabled by default.
<PropertyGroup>
<ImplicitUsings>disable</ImplicitUsings>
</PropertyGroup>
To re-enable.
<PropertyGroup>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
Adding Usings to Implicit Usings
You can add or remove namespaces from the implicit usings list using the <Using>
element in the .csproj
file.
To add a custom namespace:
<ItemGroup>
<Using Include="MyCustomNamespace" />
</ItemGroup>
To exclude a namespace:
<ItemGroup>
<Using Remove="System.Linq" />
</ItemGroup>
Conclusion
By automatically managing common namespaces, they allow you to write cleaner, more efficient code.
Whether you use them as-is or customize them, understanding implicit usings can significantly improve your C# development experience.
Happy Coding!