Class Instances and Static Classes in C#

 

Whenever an instance created for a class, a section of memory is set aside to hold the fields for that new instance and this is commonly called the instance data.

 

We can create the instance for the class as shown below.

 

public class Employee 

{ 

   private void GetData() 

    

       //functionality 

   } 

}

 

Employee objEmp1 = new Employee(); 

Employee objEmp2 = new Employee();

 

As shown above, we created the two objects objEmp1 and objEmp2 for class Employee. That means separate memory allocated for two objects.

 

Another type of data, called shared data in Microsoft Visual Basic or static data in Microsoft Visual C#, is allocated for a class as a whole. In the case of this type of data, however, only one place in memory is reserved for the data, no matter how many instances of the class exist. Every instance of the class has access to this one copy of the data as shown below.

 

public class Employee 

{ 

   public static void GetData() 

   {

       //functionality

   } 

} 

 

Employee.GetData(); 

Employee.GetData();

 

Properties, constructors, methods, and events can also be shared across class instances. These shared members, which don’t require an instance of the class, provide services related to the class. An example is the .NET Framework’s Integer.Parse method, which takes a string argument and returns an Integer value. It makes sense that the Integer class would know how to parse a string into an Integer, but obviously the Integer value doesn’t exist until the string is parsed. It also wouldn’t make sense to create an Integer value just so that you can call the Parse method to create a second instance of the Integer class. Static members are also used to manipulate the shared and static data of a class. For example, just as you’ve create properties to expose fields, you’ll create shared properties to expose shared fields. Shared and static properties, constructors, and methods have a limitation in common: they can use only the shared or static fields of a class. These members have no access to any of the instance data. Offsetting this limitation is the ability to call these methods even if you haven’t created an instance of the class.