Static
- Static is a keyword in C#, used to create class level (global) members, i.e. they are common for all the instance of a class. they are directly accessible via class name.
- We can declare static variable,property, methods.
- We can use access modifier with static members, i.e they can be public,private,etc.
- Static methods can access static variable,methods inside it.
- We can declare static constructor to initialize static member.
- Static constructor can not have parameters and access modifiers, i.e we can not apply public ,private,etc modifier on static constructor.
- Static constructor always called before instance constructor of a class.
- If we have static constructor in derived class and also in base class then call hierarchy would be
- Derived static constructor.
- Base static constructor.
- Base instance constructor.
- Derived instance constructor.
Static and Inheritance:
- Static members also inherited i.e. Static members are available in derived class, we can use them in derived class, also they are accessible via derived class name if they are public.
- We can't override static methods in derived class, if we create a static method in derived class with same signature as base class, derived class method will hide base class method.
- for example we have a static method M1() in class A, and we are creating again a static method M1() in derived class B. A.M1() will reference base class's static method while B.M1() will reference B's static method.
class A
{
static A()
{
}
public static void m1()
{
Console.WriteLine("Static M!");
}
public void InstanceA()
{
Console.WriteLine("Instance method of A");
}
}
class B : A
{
public new static void m1() //hides base's static method.
{
Console.WriteLine("Providing new definition in B!");
}
public void InstanceB()
{
Console.WriteLine("Instance method of B");
}
}
public static void Main()
{
A a = new A();
a.InstanceA();
A.m1();
B.m1(); // Static method also inherited.
Console.WriteLine();
Console.Read();
}
No comments:
Post a Comment