Global Usings in C#10

C# has a lot of in-built libraries which we call DLLs or Dynamic Link Library also it provides you as a developer the liberty to create your own DLLs in the form of classes. Classes when compiled forms DLLs. Some examples of in-built DLLs in C# are List<>, Enumerable<>, Queryable<>, ArrayList<>, etc all are from System.Collections namespace which has these classes and converted into DLLs after building the solution. Now, to use them in our class we need to tell the compiler the source of these types so that compiler can link them to basically know how they are going to work. To tell the compiler about this we use “using” statements on the top of our class file like below:-

In the above screenshot, you can see the using statement followed by the namespace which is System.Text.Json which is defining the source of JsonSerializer class. So, basically, the compiler now knows okay the JsonSerializer is coming from this location and is doing what.

Now, if we remove this using statement the compiler will be angry and will throw a compile-time error.

Now, when we code to implement any feature these using statements create a bunch of lines at the top of every class. And it is very possible that a number of classes have the same repeated using statements which leads to code duplicity. To avoid this C# 10 have the “global usings” feature, which allows you to define usings in a single class file with global keyword and its scope will be through that whole project. It’ll look like this:-

declaring global usings

And after defining the global using statement in a separate class, our main class will look like:-

with global using

You can see the using statement is commented and the compiler is also happy and not throwing any error.


Himanshu M.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store