← C# from Scratch
Lesson 23 of 39 · 10 XP
Methods
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
A method is a named block of code that you can call many times. In a program with top-level statements, methods are declared right in the file (these are local functions); in classes, they go inside the class:
using System;
Greet();
Greet();
Console.WriteLine(Square(7)); // 49
static void Greet() // void — returns nothing
{
Console.WriteLine("Hello!");
}
static int Square(int x) => x * x; // an expression body: a short form of return
- the return type goes before the name:
int,string,bool… orvoid; returnends the method and hands back a value;- method names in C# are written in
PascalCase:CalculateDamage,IsAlive; staticmeans the method doesn't depend on an object (what that means will become clear in the "Classes and objects" lesson).
Task. Write a method static bool IsPrime(int n) and use it to print all the prime numbers from 2 to n
(n is read from the input), separated by spaces.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.