Object Oriented Programming

Static Methods in C#

Static methods are methods that are called on the class itself, not on a specific object instance. The static modifier ensures implementation is the same across all class instances. In other languages, these are known as 'class methods'.


Syntax
public class className {
    modifier static dataType methodName (inputParameters) { //static method
         //block of code to be executed
    }
}

//calling the method, from anywhere
className.methodName(passedParams);

Notes

methodName is defined by the programmer, dataType is the data type of the result from calling the method, and modifier is the access modifier. The 'static' keyword is an additional modifier that makes the method static.

methodParameters contain data used within the method, stored using variables. Parameters are defined as: (dataType parameterName), which is the data type of the input parameter and the name of the parameter as seen within the method. There can be multiple parameters separated by a comma.

Static methods are called without instantiation. This means that static methods can only access other static members of the class (and of course, global and passed in variables), because other members are object members. They, however, can be called on an object, but this is discouraged.


Example
public class Numbers {
    public Numbers() {}
    public static int findMinimum(int number1, int number2) { 
        //3 stored in number1, 5 stored in number2
        int minimum = number2; 
        if (number1 < number2) minimum = number1; 
        return minimum; 
    }
}

int min = Numbers.findMinimum(3, 5);

Add to Slack

< Standard Methods   |   Constructor >

© 2018 SyntaxDB. All Rights Reserved.