Methods
- C# course
- Intermediate
- Lesson 3/116
- 4 min
Learn to define and call methods inside a class.
Defining methods
A method defines the behavior of a class. A method declaration has an access modifier, return type, name, parameter list and body: public void Greet() { ... }.
Here public means callable from anywhere, void returns no value, Greet is the method name, () means no parameters. The body goes inside curly braces. Method names use PascalCase: Add, PrintReport. A method is defined once and called as many times as needed.
Parameters and return
Methods can take values from outside (parameters) and return a result (return). Example: public int Add(int a, int b) { return a + b; }.
Here int a and int b are parameters; return a + b sends the sum back to the caller. Since the return type is int, return must give an int. In void methods there is no return statement or only a bare return;.
Practice Add an Add method to the Calculator class
Add a public int Add(int a, int b) method to the Calculator class with return a + b; in the body. Inside Main print the result of calc.Add(7, 5).
Starter code
using System;
class Calculator
{
// Define the Add method here
}
class Program
{
static void Main()
{
Calculator calc = new Calculator();
// Call Add and print the result
}
}Sample solution
using System;
class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
}
class Program
{
static void Main()
{
Calculator calc = new Calculator();
Console.WriteLine(calc.Add(7, 5));
}
}Expected output
12
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each part of the method signature
| Term | Meaning |
|---|---|
public |
Access modifier |
void |
Return type |
Greet |
Method name |
() |
Parameter list |
2 Complete the return statement
public int Add(int a, int b) { return ____ + b; }
public int Add(int a, int b) { return a + b; }
Explanation: return a + b; returns the sum of a and b.
3 Which is a valid method declaration?
- public Add(int a, int b) { }
- public int Add(a, b) { }
- void public Add() { }
- public int Add(int a, int b) { } Correct answer
Explanation: Access, return type, name and parameters are in the right order.