In C#, Manage Global Usings

In some everyday development contexts, importing common packages is necessary to accomplish class/method goals. This may be accomplished in C# by using the global keyword, which was added in C# 10.0, to call all commonly used packages and libraries in a single.cs file, saving us from having to import those packages into each.cs file across the project.

The example class A class is shown below. It contains a method named SampleMethod that will construct a table with two columns and one row.

namespace Global.Using.Sample
{
    internal class classA
    {
        public static void sampleMethod()
        {
            var data = new DataTable();
            data.Columns.Add("colA");
            data.Columns.Add("colB");
            data.Rows.Add("rowA", "rowB");
            Console.WriteLine("done");
            Console.WriteLine(data.Rows.ToString());
        }
    }
}

A few more classes follow suit with regard to their sampleMethods carrying out certain sample activities. Here, we can see that we are invoking the System throughout all classes. data bundle. Consequently, in this instance, rather than calling it in every class,

//ClassB.cs
namespace Global.Using.Sample
{
    internal class classB
    {
        public static DataTable sampleMethodB()
        {
            var data = new DataTable();
            return data;
        }
    }
}

//ClassC.cs
namespace Global.Using.Sample
{
    internal class classC
    {
        public static DataSet sampleMethodC()
        {
            return new DataSet();
        }
    }
}

//ClassD.cs
namespace Global.Using.Sample
{
    internal class classD
    {
        public static DataView sampleMethodD()
        {
            var data = new DataTable();
            return data.DefaultView;
        }
    }
}


//ClassE.cs
namespace Global.Using.Sample
{
    internal class classE
    {
        public static int sampleMethodE()
        {
            var data = new DataTable();
            return data.Columns.Count;
        }
    }
}


//ClassF.cs
namespace Global.Using.Sample
{
    internal class classF
    {
        public static int sampleMethodF()
        {
            var data = new DataTable();
            return data.Rows.Count;
        }
    }
}

By using the global keyword as shown below, we may call it from any class and offer the global package in all classes where it is necessary.

global using System.Data;

In this post, we learned how to use a global keyword, which will save us from having to call the same package numerous times.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories