Methods in C#
In object-oriented programming, objects are used as building blocks in developing a program. Objects encapsulate data and code to manipulate that data. The code designed to work on the data is known as Methods in C#.
Declaring Methods: Methods are declared inside the body of a class, normally after the declaration of data fields. It has the following syntax:
modifiers type method-name(format-parameter-list) { method-body ........... }
In C#, The method declaration has five parts:
- Name of the method
- Type of value the method returns
- List of parameters
- Body of the method
- Method modifiers
Method-name is a valid C# identifier. The Type specifies the type of value the method will return. This can be a simple data type such as int as well as any class type. If the method does not return anything, we specify a return type of void.
The format-parameter list is always enclosed in parentheses. The list contains variable names and types of all the values we want to give to the method as input. The parameters are separated by commas. In the case where no input data are required, the declaration must still include an empty set of parentheses() after the method name.
Example:
int add(int x, float y, float z) // three parameters void display() // no parameters
The modifiers specify keywords that decide the nature of accessibility and the mode of application of the method. A method can take one or more of the modifiers listed below:
Modifier | Description |
new | It can hide an inherited method with the same signature. |
public | It can be accessed from anywhere including outside the class. |
protected | It can be accessed from within the class to which it belongs. |
private | It can only be accessed from inside the class to which it belongs |
internal | It can be accessed from within the same program |
static | It doesn't operate on a specific instance of the class. |
virtual | It can be overridden by a derived class |
abstract | It is a virtual method which defines the signature of the method. |
override | It can override an inherited virtual or abstact method |
sealed | It can override an inherited virtual method but it can't be overridden by any classes which inherit from this class. |
extern | It can be implemented externally in a different language. |