Introduction
There are scenarios in day-to-day development where we need to import common packages to achieve class/method objectives. In C# this we can achieve using the global keyword introduced in C# 10.0 so that we can call all common using packages/libraries in single .cs file which will help us not to import those packages in every .cs file within the project.
Below is the sample classA class, which has a method with name SampleMethod, which will create table with 2 columns and 1 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());
}
}
}
Similarly few more classes w.r.t their sampleMethods performing some sample actions. Here we can see that in all classes we are calling System.Data package. So in this case instead of calling it in each and 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;
}
}
}
We can call it in any one class by using global keyword like below, which will help us to provide that global package in all classes were it's required.
global using System.Data;
Summary
In this article, we understood use case of global keyword which will help us to avoid calling multiple places for calling the same package.