Static in c#
Static Keyword enforce not to create the constructors.Only one copy
of static fields and events exists, and static methods and properties can only
access static fields and static events.It is not possible to create instances
of a static class using the new keyword.Instead,
you will access members of the static class by using the class name.
Static classes are loaded automatically by the .NET Framework common
language runtime (CLR) when the program or namespace containing the class is
loaded.Static class are sealed,which means that they cannot be inherited and
cannot inherit from any class other than System.Object and can have only static
members,static properties and Static methods.
A static member belongs to the class rather than to
the objects of the class.You can't use this keyword
with static, as it will not initialize. Static members are shared level and are
not initiated.
Important Points
on static
1.If a static constructor throws an exception, the runtime will not
invoke it a second time, and the type will remain uninitialized for the
lifetime of the application domain in which your program is running.
2.Property available to callers at any time, even if no instance of
the class exists.
3.Only classes can be declared as static and not structs.
4.You can't use this keyword with
static, as it will not initialize. Static members are shared level and are not initiated.
5.Static methods can be public or private.
6.Static modifier cannot used with indexers, destructors, or types.
Example:
public static class Calculation
{
public static double ADD(double i, double j)
{
return i + j;
}
}
class Program
{
static void
Main(string[] args)
{
//Error:-
Cannot create an instance of the static class'Calculation'
//Calculation cal = new
Calculation();
double Res= Calculation.ADD(10,
20);
Console.WriteLine("Add
{0}", Res);
}
}
Result:
Add 30