Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Creating and Calling Methods | Methods
C# Basics
course content

Course Content

C# Basics

C# Basics

1. Getting Started
2. Dealing with Data Types
3. Control Structures
4. Loops
5. Arrays
6. Methods

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:

cs

main

copy
123
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:

cs

main

copy
123456
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:

cs

main

copy
1
methodName();

We can execute the countToTen method in the following way as we explored in the last chapter:

cs

main

copy
1
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:

cs

main

copy
123456789101112131415161718192021
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.

What will be the output of the following code? (This quiz can be a lesson in itself that meaningful method naming matters)

Select the correct answer

Everything was clear?

Section 6. Chapter 2
We're sorry to hear that something went wrong. What happened?
some-alt