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)

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.

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:

newIt can hide an inherited method with the same signature.
publicIt can be accessed from anywhere including outside the class.
protectedIt can be accessed from within the class to which it belongs.
privateIt can only be accessed from inside the class to which it belongs
internalIt can be accessed from within the same program
staticIt doesn't operate on a specific instance of the class.
virtualIt can be overridden by a derived class
abstractIt is a virtual method which defines the signature of the method.
overrideIt can override an inherited virtual or abstact method
sealedIt can override an inherited virtual method but it can't be overridden by any classes which inherit from this class.
externIt can be implemented externally in a different language.