TOC

This article is currently in the process of being translated into Portuguese (~19% done).

Classes:

Methods (functions)

Enquanto propriedades e campos podem ser considerados partes passivas de uma classe, métodos são ativos. Eles desempenharão uma ou várias ações e, opcionalmente, retornarão um resultado. Em outras linguagens de programação eles são, às vezes, referidos como functions (funções) ou até "funcs", porém, no C#, quando pertencem a uma classe, são chamados de métodos. Métodos são bem úteis, pois te dão a possibilidade de encapsular um pedaço de funcionalidade em um método, o qual você pode, então, chamar novamente por vários lugares.

A method is defined like this:

<visibility> <return type> <name>(<parameters>)
{
    <method code>
}

Aqui está um exemplo muito básico:

public int AddNumbers(int number1, int number2)
{
	return number1 + number2;
}

Este método muito básico adicionará dois números e retornará o resultado. Vamos percorrer as várias partes dele:

  • public is the visibility (more on that later in this tutorial)
  • int is the return type. If you don't want your method to return anything, use the void keyword instead
  • AddNumbers is the name of the method
  • (int number1, int number2) - these are the parameters (more on those later). Parameters are optional, so you are free to leave the space between the parentheses empty. The parentheses are not optional though.
  • Inside the method (between the curly braces), you will find the actual code of the method. It can be one or many lines of code.

To call a method, simply write it's name followed by a set of parentheses. Inside the parentheses, you should write the parameters (if the method accepts any), like this:

AddNumbers(3, 39);

Since methods are defined on classes, you may want to call a method on another class than the one you are currently in. If so, you should prefix the method call with the name of the object, or in case of a static method (more on those later), the name of the class. Here's an example where we call the AddNumbers() method, which has been placed in another class called MathHelper:

public void DoMath()
{
	MathHelper mathHelper = new MathHelper();
	int result = mathHelper.AddNumbers(4, 38);
	Console.WriteLine(result);
}	

Method return types

Let's talk more about return types. In the examples above, we defined a method with an integer as the return type, but you are free to return any other kind of C# data type. In fact, you can even declare a method which doesn't return anything, as we saw with our DoMath() method above. Notice that I have substituted int with the void keyword, which means that this method is not supposed to return anything. In some programming languages, functions without a return type are referred to as procedures, but in C#, they are always called methods.

You should be aware that when you declare a return type for a method, you HAVE to return something - otherwise, the compiler will immediately complain:

public int AddNumbers(int number1, int number2)
{
	Console.WriteLine(number1 + number2);
}
Compiler error: AddNumbers(int, int)': not all code paths return a value

This means that you need one (or several) return keywords inside your method if it has a declared return type. You may need more than one for situations where you have multiple possible code paths, like this:

public int AddLargeNumbers(int number1, int number2)
{			
	if((number1 > 1000) && (number2 > 1000))
	{
		return number1 + number2;
	}
	return 0;
}

In this case, we need the second return statement as well - if it's omitted, the compiler will complain, because our conditional statement could prevent the first return statement from being hit.

Summary

Methods allow you to encapsulate and reuse functionality from several places. By supplying different parameters to a method, you can get different results. We have used some parameters in the examples above, but in the next article, we'll dig much deeper into the subject of method parameters.

This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!