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
- Class Class1
- {
- int a;
- static int b ;
- }
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.
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.
Now create three instances of the Class1 in the Main Method in the Program.cs file. (See the figure.)
Debug the application and see the output.