Course Content
C# Basics
C# Basics
Creating and Calling Methods
In the last chapter, we looked at the concept of methods. In this chapter, we will look at the syntax for creating methods and using them.
A very basic method can be created using the following syntax:
main
static returnValue methodName(parameters, ...) { // code to be executed when the method is called }
We will be exploring returnValue
and parameters
in the later chapters, for now we will use void
as the returnValue
and nothing in place of parameters as they are optional. For-example, we can create a method called countToTen
from the previous chapter:
main
static void countToTen() { for(int i = 0; i < 10; i++) { Console.Write(i + " "); } Console.WriteLine("END"); }
We can execute a method using the following syntax:
main
methodName();
We can execute the countToTen
method in the following way as we explored in the last chapter:
main
countToTen();
Note that this way of calling a method only works with a method that is static
and void
and has no parameters. In the later chapters, we will learn about the term void
and how to make a method that has parameters, along with how to call such methods.
You don't need to understand the static
part in detail on this level but to understand static
you should know that a method is always a part of a class:
main
using System; namespace ConsoleApp { class Program { static void countToTen() { for (int i = 0; i < 10; i++) { Console.Write(i + " "); } Console.WriteLine("END"); } static void Main(string[] args) { countToTen(); } } }
The above is how a method will look like in a full program. In this case the class is called Program
. If we don't use the term static
before a method then it means we cannot use that method until an instance if a class is created, which might not make a lot of sense in this chapter so right now you don't need to worry about all the complexities of the term static
.
Everything was clear?