Object Oriented Programming

Standard Methods in C#

A method is a block of code that can be called from another location in the program or class. It is used to reduce the repetition of multiple lines of code. The return statement concludes the execution of the block of code, returning something of type provided in the method header, or null (void method).

Within a class, these are known as 'instance methods'. An instance method is tied to a class instance.


Syntax
///method declared within a class
modifier dataType methodName (methodParameters) { 
   ///statements that execute when called 

   return value; ///optional return statement
}

///calling a method within a class
returnVariable = methodName(passedParameters);
///calling a method outside a class
classInstance.methodName(passedParameters);

Notes

An instance method is tied to the specific class instance, so outside the class it must be called on the class instance.

The (optional) access modifier determines where the program can call the function.

methodName is defined by the programmer, dataType is the data type of the result from calling the function.

methodParameters are the inputs needed for the function to execute. 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 function.

There can be multiple parameters separated by a comma.


Example
public class Math {
    Math() {}
    int findMaximum(int number1, int number2) { 
       int maximum = number2; 
       if (number1 > number2) 
          maximum = number1;
       return maximum; 
    }
}

///method call, outside of the class
Math calculator = new Math();
int max = calculator.findMaximum(2, 5);

See Also
Documentation

Methods (C# Programming Reference

Add to Slack

< Class Variables   |   Static Methods >

© 2019 SyntaxDB. All Rights Reserved.