2. Basic Syntax

·

1 min read

import namespace

Global import

C# >=10 support global keyword. If import namespace with global keyword, that namespace can available over all .cs file.

# GlobalUsings.cs
global using System;

It can be done by adding ImplicitUsings attribute on the .csproj file. This attribute will add frequently used namespace such as System. Also, adding Using attribute inside of ItemGroup on .csproj does the same thing as global keyword.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <Using Include="System" />
  </ItemGroup>

</Project>

If ImplicitUsing attribute is enabled, SDK automatically generate <ProjectName>.GlobalUsings.g.cs under /obj/debug/net7.0.

This file looks like this.

// <auto-generated/>
global using global::System;
global using global::System.Collections.Generic;
global using global::System.IO;
global using global::System.Linq;
global using global::System.Net.Http;
global using global::System.Threading;
global using global::System.Threading.Tasks;

Reference

MS Dev blog - Explanation about import statement is good