Static Methods in C#
Introduction
The
methods in C# may or may not take parameters and they may or may not return a
value. Also, a custom method that is also known as user defined methods may be
declared non-static (instance level) or static (class level). When a method is
static then it can be invoked directly from the class level without creating an
object. This is the reason for making main() function/method to be static. The
another example is WriteLine() method that is called/used without creating any
object. Let’s have some chat in example.
class Program
{
public static void withoutObj()
{
Console.WriteLine("Hello");
}
static void Main()
{
Program.
withoutObj();
Console.ReadKey();
}
}
In
above example, I will be calling method using class name itself and no any
WriteLine() object is used.
Using Static Method
Usually
we define a set of data members for a class and then every object of that class
will have separate copy of each of those data members. Let’s have a example.
class Program
{
public int myVar; //a non-static field
static void Main()
{
Program
p1 = new Program(); //a object of class
p1.myVar = 10;
Console.WriteLine(p1.myVar);
Console.ReadKey();
}
}
In
above example, myVar is a non-static field so to use this field we first need
to create the object of that class. On the other hand, static data is shared
among all the objects of that class. That is, for all the objects of a class,
there will be only one copy of static data. Let’s have a example.
class Program
{
public static int
myVar; //a
static field
static void Main()
{
//Program
p1 = new Program(); //a object of class
myVar = 10;
Console.WriteLine(myVar);
Console.ReadKey();
}
}
In
above we don’t have object of class to use that field it is only because of
field is static.
Notable Points here are:
1.
Static method can be invoked directly from class level
2.
Static method not requires any class object
3.
Any main() method is shared through entire class scope so it always appears
with static keyword.
Comments
Post a Comment