- A static class cannot be instantiated
- Static classes are sealed and therefore cannot be inherited.
static class Abc{ }
compiles
to this IL:
.class private abstract auto ansi sealed beforefieldinit Abc
extends [mscorlib]System.Object
{
}
- Static methods can be overloaded but not overridden
- Creating a static class is same as a class that contains only static members and a private constructor, because private constructor prevents the class being instantiated.
- Static methods are held only once in a memory.
- They cannot contain instance constructors.
- Example
using System;
class Program
{
static void Main()
{
StaticClass.StaticMethod();
Console.ReadLine();
}
}
static class StaticClass
{
internal static void StaticMethod()
{
Console.WriteLine("Inside
Static Method");
}
}
- O/P
- Static Constructor
- These are used to initialize any static data, only once
- A static constructor has no parameters
- It is run automatically by the run time. It is guaranteed to run at most once even if two threads arrive at the same time.
- Example (Console class)
Console.WriteLine("Anurag");
Console.ReadLine();
No comments:
Post a Comment