Static Members of the class in .Net
Static members belong to the whole class rather than to individual object
Static members are accessed with the name of class rather than reference to objects.
Example of Static Mebers in .Net Class
class Test
{
public int rollNo;
public int mathsMarks;
public static int totalMathMarks;
}
class TestDemo
{
public static void main()
{
Test stud1 = new Test();
stud1.rollNo = 1;
stud1.mathsMarks = 40;
stud2.rollNo = 2;
stud2.mathsMarks = 43;
Test.totalMathsMarks = stud1.mathsMarks + stud2.mathsMarks;
}
}
Static Method of the class in .Net
1) Methods that you can call directly without first creating an instance of a class. Eg: Main() Method, Console.WriteLine()
2) You can use static fields, methods, properties and even constructors which will be called before any instance of the class is created.
3) As static methods may be called without any reference to object, you can not use instance members inside static methods or properties, while you may call a static member from a non-static context. The reason for being able to call static members from non-static context is that static members belong to the class and are present irrespective of the existence of even a single object.
No comments:
Post a Comment