Methods
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;.
Exercise 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).
Show example solution
Define Add to return int. In Main write Console.WriteLine(calc.Add(7, 5));.
Example 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));
}
}
Test yourself
-
Match each part of the method signature
- public
- Access modifier
- void
- Return type
- Greet
- Method name
- ()
- Parameter list
-
Complete the return statement
public int Add(int a, int b) { return ____ + b; }Show answer
public int Add(int a, int b) { return a + b; } -
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) { }
Show answer
public int Add(int a, int b) { } — Correct. Access, return type, name and parameters are in the right order.