Working With Instance and Static Data Members of a Class in C#

Working with instance and static data members of a class. We can declare two types of data members in a class, instance type or static type. By default the data members declared in a class are of instance type.
 
To declare a member as a static type we add a prefix Static during the member declaration.
 
 Syntax

  1. Class Class1  
  2. {  
  3.      int a;//instace type  
  4.      static int b ;// static type  

 Demo Program
 
 An instance data member of a class is recreated each time when a new instance of the class is created and it is associated with that instance only.
 
 Whereas a static data member of a class is not recreated with new instance creation, only one copy of it is shared by all the instances.
 
 See the following figure.
 
instances 
 Demo program showing the use of static type and instance type.
 
 Create a Console Application in C# in Visual Studio 2010. Add a class to the project, in other words Class1.cs. Write the code as shown in the figure.

Add a class
 Now create three instances of the Class1 in the Main Method in the Program.cs file. (See the figure.)

Main Method
 Debug the application and see the output.

output

Up Next
    Ebook Download
    View all
    Learn
    View all