Global usings in C#
image taken from unsplash

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:-

No alt text provided for this image





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:-

No alt text provided for this image




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

No alt text provided for this image






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.

要查看或添加评论,请登录

Himanshu Motwani的更多文章

  • Creating a Singleton service in Angular

    Creating a Singleton service in Angular

    Angular services come into the picture when you need to call an API to fetch some data from Server in your front-end…

社区洞察

其他会员也浏览了