25 December 2013

c# methods explained in detail

When programming you use classes, methods, properties and data members, etc. In this tutorial let's discuss methods in C# language.

  1. What is a method?
  2. What constitute a method?
  3. A typical method in C# language
  4. Types of methods

What is a method?

A method usually performs something when it is invoked. What a method performs, depends on what logic you put in the method body.

For example, consider a Car class; We can define Drive() method to drive the car forward and Reverse() method to go reverse. Here both Drive() and Reverse() methods perform some actions, they modify the state of the object. i.e., Car position.

Consider a Television set's remote control example; It controls the behaviour of the television. You can implement VolumeUp(), VoulmeDown(), ChangeChannel() and ScanChannels(), etc, methods to control the behaviour of the TV.

What constitutes a method?

  1. Method name:

    Used to identify a method and invoke the method.

  2. Method arguments or parameters:

    A method can have multiple or no parameters. Method arguments can be of different types based on your requirements.

  3. Method body:

    Method body defines the behaviour. It is the crux of the method.

  4. Method return type:

    A method can return a single entity or its return type can be void, returning nothing

  5. Method access specifier:

    Used to define the visibility of the method. Using method access specifier developer defines, who can invoke the method and who cannot invoke it. It can be any of the C# access specifier i.e., private, internal, protected, internal or protected internal.

  6. Method name, argument list, return type and access specifier together forms the method signature.

A typical method in C# language

As always going through an example is better idea to understand something new. Let's consider the below C# class, Calculator.
public class Calculator
    public long Add(int a, int b)
       // method logic...
       int sum = a+b;
      // Method is returning
       return sum;
In the above C# code example, Calculator is a class and has a method Add().
  1. Add is a method name.
  2. (int a, int b) is an arguments list. Where a & b is parameters of integer type.
  3. What you can see within the { flower brackets } is method body.
  4. At the end of the method body, there is a return statement, returning sum. Method execution stops when the control flow in a method encounters a return statement.
  5. The Add() method has public access specifier, meaning anybody who can use the class can invoke the method. i.e. It's visible to all.

Types of methods

There are different method types. Let's go one by one briefly:
  1. Instance methods
  2. Static methods
  3. Constructors & Destructors methods
  4. Abstract & concrete methods
  5. Virtual & overridden methods
  6. Overloaded methods
  7. Partial methods
  8. Extension methods

Instance methods

Method which can only be invoked using class instance are called instance method. i.e., in the above Calculator class, the Add() method can be invoked using the instance.

Calculator calculator = new Calculator();
long sum = calculator.Add(100, 200);

Static methods

Methods can be declared static, meaning using class itself such method can be invoked. Using class instance such methods cannot be invoked.

Always declare a method as a static method, if doesn't use any instance members. Static methods perform little better compared to instance methods.

Let's add a static method to the Calculator class and see how it can be invoked.

public class Calculator
    public static void DisplayManufacturer()
  // static method invoked using the Calculator class.

Constructors & Destructors methods

Constructor and Destructors are also method in the class, but they are special methods. Constructors are used to create an instance of a class and Destructors used to destroy the objects.

Constructors can have one, multiple or no parameters. The Constructor without any parameter is referred as default constructor. Even if the developer doesn't define a parameterless constructor they exist by default. Constructors don't have a return type; their return type is implicit. i.e. It can only return the same class object.

public class Calculator
   public string Model{get;set;}
   public Calculator(string model)
        this.Model = model;

// Instance created using the parameterless constructor.
Calculator calculator= new Calculator();

// Instance created using the parameter constructor.
Calculator calculator= new Calculator("2012-FC");

Destructors are also called finalizers. Destructors cannot have any parameters. In C# .NET they cannot be invoked by developers, they get invoked by the framework during the Garbage collection process.

Let's consider an example of Destructors with the same Calculator class:

public class Calculator
   // Finalizer method

Abstract & concrete methods

Abstract methods are declared as abstract and just have method declaration. The abstract methods will not have method definition or method body. A class containing a abstract method should be declared a abstract class. In the C# code sample, the Car class has the Drive() method which is an abstract method.

public abstract class Car
   public abstract Drive();

The method which has the definition or provide implementation are called concrete methods. In this post, the Caluculator class's Add() method is an example of concrete method.

Virtual & overridden methods

Methods can be declared as virtual; meaning such method can be overridden in the derived class. When writing a class if you think derived class can customize the behavior then mark the method as virtual.

Methods declared virtual in derived class, can be overridden by the derived class to customize the behavior accordingly.

Refer article, Function overriding in C# .NET for more details on Virtual & overridden methods

Overloaded methods

Method can be overloaded in a class or struct to achieve compile time polymporphism. Methods with the same name and varying parameter list by number and data types of arguments are called overloaded methods.

Partial methods

Partial methods can be declared in one partial class and have implementation in another same name partial class. Partial methods are introduced for situations where you are generating code automatically using tools.

Refer another detailed tutorial on partial methods in C# .NET to know in detail.

Extension methods

Extension methods adds a method to class without modifying the class definition, so it's useful in adding method to a third party class within a namespace scope. To understand more go through tutorial on C# extension methods.