What are Static Members?
- To understand this, just think about the meaning of static, It means stationary(unmoving).
- In C#, It can be anything like Method, Attribute, Class etc.
- Static Member are member that are not called by the instance of the class and is directly accessible by the class name.
- We use a static modifier to make a member static.
Static Class and Non Static Class:
- Static Classes are classes which contain only static members
- We can not make a instance of this class, because why would we want it as there is no non static member in it to call them by using the instance of class.
- Non Static Classes are classes that can contain static as well as non static members and we can make instance of these classes so that we can use its non static members by using its object.
Example of Static Class:
static class Student
{
int Shahzaib_Marks; // error will occur as we can not declare non static (that
can be instantiated) member in a static class
static int Amir_Marks; // Everything is alright here
}
Example of Non Static Class:
class Student
{
int Shahzaib_Marks; // we can take static or non static members
static int Amir_Marks; // we can take static or non static members
}
Static and Non Static Fields:
•
Static Fields are same in the all objects of the
class because object does not affect any static member as we do not need an
object to access a static field.
•
Non Static Fields are not same in all objects as
they are accessed by the different objects.
Example of Static and Non Static Fields:
class Student
{
public int Shahzaib_Marks;
public static int Amir_Marks;
}
class calling
{
public calling()
{
Student s = new Student();
s.Shahzaib_Marks = 10; //
accessed by object because it is non static
Student.Amir_Marks = 10; // accessed by class name because it is static
}
}
Static Methods:
Static Methods are just like Normal methods but they can not be accessed using the object of the class and it does not access class level non static members.
Hit Like Button if you understood, It helps a lot to keep us Motivated.
class Program
{
static void Main(string[] args)
{
student.study(); // static method
called by class name
student s = new student();
s.read(); // non static method called by object of the class
}
}
class student
{
public static void study()
{
Console.WriteLine("Static
Method Called");
// you can not call non static member in a
static method
practice(); // you
can call a static member in a static member
}
public static void practice()
{
Console.WriteLine("Second Non
Static Method Called");
}
public void read()
{
Console.WriteLine("Not static
Method Called");
study(); // you
can call static member in a non static member
}
}
http://ghulamahmedbinsaeed.blogspot.com/
ReplyDeleteDownload Games | Softwares | Learning | Ethical Hacking | By-Passing | I-Phone jail Break | Mobile Hacking | All about Technology | News And reviews | Latest Android And Symbian Applications | Tutorials | And Much more For you