How do you recognize a method call in C#?
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.
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.
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.
Related C# job interview questions
What C# data types do you know?C# Junior
What is a data type?C# Junior
What is a method in C# and how do you define one?C# Junior
What is a constructor in C# and why would you use it?C# Junior
What parts does a C# class usually contain?C# Junior