static data field in C-Sharp / C#

Data members of a class in C# can be defined as static. The value of data member will be same for all the objects created of the class since the static data member is a class variable.

The static data member of a class can be accessed using ClassName.DataMember.
Most of the time when designing a class, you define data as instance-level data; said another way, as nonstatic data. When you define instance-level data, you know that every time you create a new object, the object maintains its own independent copy of the data.
In contrast, when you define static data of a class, the memory is shared by all objects of that category.

To see the distinction, create a new Console Application project named StaticDataAndMembers.
Now, insert a new class into your project named SavingsAccount. Begin by defining a point of instancelevel
data (to model the current balance) and custom constructor to set the initial balance:

Code Snippet
  1. // A simple savings account class.
  2. class SavingsAccount
  3. {
  4.     // Instance-level data.
  5.     public double currBalance;
  7.     public SavingsAccount(double balance)
  8.     {
  9.         currBalance = balance;
  10.     }
  11. }

When you create SavingsAccount objects, memory for the currBalance field is allocated for each
object. Thus, you could create five different SavingsAccount objects, each with their own unique balance.
Furthermore, if you change the balance on one account, the other objects are not affected.
Static data, on the other hand, is allocated once and shared among all objects of the same class
category. Add a static point of data named currInterestRate to the SavingsAccount class, which is set to
a default value of 0.04:

Code Snippet
  1. // A simple savings account class.
  2. class SavingsAccount
  3. {
  4.     // Instance-level data.
  5.     public double currBalance;
  7.     // A static point of data.
  8.     public static double currInterestRate = 0.04;
  10.     public SavingsAccount(double balance)
  11.     {
  12.         currBalance = balance;
  13.     }
  14. }

Here, our assumption is that all saving accounts should have the same interest rate. Because static
data is shared by all objects of the same category, if you were to change it in any way, all objects will
“see” the new value the next time they access the static data, as they are all essentially looking at the
same memory location. To understand how to change (or obtain) static data, we need to consider the
role of static methods.

Post a Comment