Global usings in C#
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.
So, 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:-
领英推荐
And after defining the global using statement in a separate class, our main class will look like:-
You can see in the above image that the using statement is commented and the compiler is also happy and not throwing any error.
Thanks,
Himanshu M.