How do you recognize a method call in C#?

Experience Level: Junior
Tags: C#

Answer

In C# there are several ways how to call a method. Both ways have one thing in common. You can always see a name of the methd and opening and closing rounded brackets following the name.

If there is a dot or space before the method name and there isn't a data type before it, it is a method call.

Let's have a look at couple of examples.

The first way how you can call a method is to call one method from another method where both methods are defined within the same class.

In the example below, if someone calls the method TurnOn(), the method TurnOff() will automatically be called by the method TurnOn().

So whenever someone turns the radio on, it will automatically turn itself off. Yeah, it's a bit useless radio this way, right? But at least it does something.

Example
public class Radio()
{
  public void TurnOn()
  {
    TurnOff();
  }
  
  public void TurnOff()
  {
    // Some code here
  }
}

The second way is when you call one method from another method where each method is defined within a different class and the called method is called on an instance of a class.

In the example below, when the Program is executed and the method Main is called, the new radio object is created and then the metod TurnOn()
is called on this newly created object.

Example
public class Program
{
  public static void Main()
  {
    var myRadio = new Radio();
	myRadio.TurnOn();
  }
}

public class Radio
{
  public void TurnOn()
  {
    // Some code here
  }
  
  void TurnOff() {
    // Some code here
  }  
}

The third way way how to call a method is to call one method from another method where each method is defined within a different class and the called method is called directly on a class without an instance of an object to be created.

Such method must be marked by the keyword 'static'.

In the example below, not that when we are calling the method PrintHello(), there is no instance of class Printer created.

We are calling the method directly on a class Printer.
 

Example
public class Program
{
  public static void Main()
  {
    Printer.PrintHello();
  }
}

public class Printer
{
  public static void PrintHello()
  {
    //
  }
}

Comments

No Comments Yet.
Be the first to tell us what you think.
C# for beginners
C# for beginners

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

Test yourself