In this article we will discuss how we can call or invoke a method in c#. Once any method have been defined, then we activate that method. The process of activating method is called by invoking method. We use dot operator for invoking method like as:
oMethod(parameters);
Where oMethod is the method name and oParameters is the given list of parameters.
Calling method from another class
In the following example a method named GetArea and is used to calculate the area of the square on the basis of value passed as parameter.
using System; using System.Windows.Forms; class Area { public void main() { Shape objShape = new Shape(); double areaOfSquare = objShape.GetArea(15, 56); } } class Shape { public double GetArea(double length,double width) { return (length * width); } }
from the above, before calling GetArea method, we create object of the class Shape.
Calling a static method
Suppose if we declare GetArea() method in the same class where we call that method, wecan invoke GetArea method without creating any object of the class. see this:
using System; using System.Windows.Forms; class staticMethod { public void main() { double areaOfSquare = GetArea(15, 56); } public double GetArea(double length, double width) { return (length * width); } }