What do you know about methods in C#?

Experience Level: Junior
Tags: C#

Answer

Methods contain code that does something. They are like boxes that encapsulate its content.

Each method consists of method signature and method body.

The method signature is composed of method name, method parameters, method return data type and access modifier.

The method body contains code.

You can run the code that is in the method body by calling the method.

The first part of the method signature is an access modifier. It defines whether the method is visible to the external code and whether it can be called. Two basic access modifiers are public and private.

The second part of the method signature is method return data type. It defines what type of result will be returned by the method after it is called. It can be number, string, bool or any other data type.

The third part of the method signature is method name. Method name should be short and it should describe what the method does. Giving a method a good name that the others will understand is one of the important skills of good programmers.

A method can be either instance method or static method.

The instance method cannot be called without having an instance of class created. You have to first create an object and then you can call the instance method using the object.

The static method doesn't need an instance of class created. You can call the method directly on a class. Such method however cannot access values from the object (because the object was never created).

In the following example, we can see:

 

  • the access modifier is 'public' which means the method is visible to all code.
  • the return data type is 'int', which means the integer number will be returned by the method as a result of its execution.
  • the name of the method is Calculate

 

The method has:

Example
public int Calculate(int firstNumber, int secondNumber) 
{
  var result = firstNumber + secondNumber;
  return result;
}

public static int Calculate(int firstNumber, int secondNumber) 
{
  var result = firstNumber + secondNumber;
  return result;
}
Other C# job interview questions
C# for beginners
C# for beginners

Are you learning C#? Try our test we designed to help you progress faster.

Test yourself