Static Variables and Static Methods
Each object has its own set of member variables and all the member variables have a scope.
If we want a variable to have the same value throughout all instances of the object then we can declare it as a static variable in our program. To manipulate and use the values of static variables we can also define a function as static.
The keyword "static" means that only one instance of a given variable exists for a class. Static variables are used to define constants because their values can be retrieved by invoking the class without creating an instance of it.
Static variables can be initialized outside the member function or class definition. The following code is an example of a static variable, which shows the declaration and initialization of a static variable.
using System;
namespace staticexample
{
class Program
{
public static int i;
public static void display()
{
i=10;
Console.WriteLine(i);
}
public void demo()
{
int j=20;
Console.WriteLine(j);
}
static void Main(string[] args)
{
Program obj = new Program();
Program.display();
obj.demo();
Console.Read();
}
}
}
Here we have not used an instance of the class for the static method display(). However, for the nonstatic demo() method we need the instance of the class to call it. This is how to call static and non-static methods.
Note
Unlike other member variables, only one copy of the static variable exists in memory for all the objects of that class. Therefore, all objects share one copy of the static variable in memory.
Objects
An object is an instance of a class. We create objects to access member variables and member functions of a class. To use the member of a class, we need to create an object of the class. Objects interact with each other by ing messages and by responding to the received messages. In C# , the task of ing messages can be done using member functions.
class Program
{
static int x, y;
void display()
{
int result = x + y;
Console.WriteLine("the result is " + result);
}
static void Main(string[] args)
{
Console.WriteLine("enter the numbers");
x=Convert.ToInt16(Console.ReadLine());
y=Convert.ToInt16(Console.ReadLine());
Program obj=new Program();
obj.display();
Console.ReadLine();
}
In the code above we have declared a class named "Program". To create an object of the class named "obj", the following code is given in the Main() method:
Program obj=new Program();
The member function of the class is accessed through an object of the class using the "." operator, as shown in the following example:
obj.display();
The code above is used to access the member function display(). This means that the object obj of the class Program has invoked the function display(). This function calculates the result and displays it on the console.