C# Tutorial For Beginners: Working Static Elements
Updated: Jan 19, 2022
Static elements are essential as they can upgrade the efficiency and clarity of the program. Static variables provide the power to create a single variable that is created a single time and can be used for all instances of the class.
Here is an example that can demonstrate the use of static elements:
Static Variable
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Total Money In Bank without customers: " + BankAccounts.TotalMoneyInBank);
BankAccounts ClientA = new BankAccounts();
BankAccounts ClientB = new BankAccounts();
BankAccounts ClientC = new BankAccounts();
Console.WriteLine("Total Money In Bank after adding customers: " + BankAccounts.TotalMoneyInBank);
Console.ReadKey();
}
class BankAccounts
{
public static int TotalMoneyInBank = 0;//Will updated per cusomter
public BankAccounts()
{
TotalMoneyInBank = TotalMoneyInBank + 100;
}
}
}
Result:

Static Variables
Static functions are executed on the class level and not for a specific object, therefore like every other component configured with 'Static,' we have a few conditions that must be applied before we can access it.
Conditions and Specifications:
Unlike a NON-static function, we can access the static function via the Class level.
Every function should be declared with the 'static' keyword.
Static functions can be used to perform calculations, Global tasks that are not relevant for a specific instance.
static void Main(string[] args)
{
Console.WriteLine(StaticExample.Calculation(10, 2));
Console.ReadKey();
}
class StaticExample
{
public static int Calculation(int num1, int num2)
{
return (num1 * num2) * 3;
}
}
Result:
