STATIC usage:
You create a class and you describe how objects of that class look and how they will behave.
You don’t actually get anything until you create an object of that class with NEW operator since from that point only
data storage is created and methods become available.
But there are two situations in which this approach is not at all needed.
One is if you want to have only one piece of storage for a particular piece of data, regardless of how many objects are created, or even if no objects are created.
The other is if you need a method that isn’t associated with any particular object of this class.
That is, you need a method that you can call even if no objects are created.
You can achieve both of these effects with the static keyword.
When you say something is static, it means that data or method is not tied to any particular object instance of that class.
So even if you’ve never created an object of that class you can call a static method or access a piece of static data.
With ordinary, non-static data and methods you must create an object and use that object to access the data or
method, since non-static data and methods must know the particular object they are working with.
Of course, since static methods don’t need any objects to be created before they are used, they cannot directly access non-static members or methods by simply calling those other members without referring to a named object
(since non-static members and methods must be tied to a particular object).
Syntax:
- public static int i = 10;
- public static void display()
- {
- //Logic
- }
Example:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
-
- namespace ConsoleApplication1
- {
- class Program
- {
- public static int iVariable = 10;
-
- public static void display()
- {
- int iMethod=20;
- Console.Write(+iMethod + "\n");
- }
-
-
- static void Main(string[] args)
- {
-
- Console.Write(+iVariable+"\n");
-
- display();
-
- }
- }
- }
- Output:
- 10
- 20
Did you notice ?
- static void Main(string[] args)
- {
-
- }
The main method is declared with Static keyword.
Since the main method is the parent method and starting point of an application, it should be executed without creating an object for it. So, C# automatically puts static keyword in the program.
..