Introduction:
Static Methods are methods that can be
accessed without creating instances of the class. Static methods supply
the easy way to call the methods based on the Flexibility in our code.
Static Methods does not require Object:
Static Methods does not require creating
instances of the class object. So we don't instantiate
MyClass obj= new MyClass ();
Creating a static Method:
Creating a static method is as simple as
creating a normal method in C#. The only different from a normal method is the
word static.
In this
example, I have created a new class named StatMethod that defines
a new static Method Add.
public static int Add(int val1, int val2)
{
return
val1 + val2;
}
The above code defines a static method Add which accpets integer paramters
and returns the sum of the Input given.
Calling a static
Method:
Since static Methods do not require
creating instance of the Class, the static method can be called using the
Syntax :
classname.methodname ( )
To call our Add Method in the Class StatMethod,
StatMethod.Add(1,2)
As this is a static Method,we don't require creating a new object of the
class StatMethod and we can call the Method
Add straight way.
Static methods provides a way to quick access to the method.
Points to Remember:
A static
method does not require creating instances.
Regarding
Performance, Static methods are normally faster to
invoke on the call stack than instance method
Thanks for reading.