Lesson #16 - Working Static Elements

Static elements are very important as they can upgrade the efficiency and clarity of the program. Static variables provide the power to create a single variable that 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 few conditions that must be applied before we can access it.


Conditions and Specifications:

  1. Not like a NON-static function, we can access static function via Class level.

  2. Every function should be declared with the 'static' keyword.

  3. Static functions can be used to perform calculations, Global tasks that 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:





2 views0 comments