Void Methods
Part of the Fundamentals section of Coddy's C# journey — lesson 54 of 69.
In C#, a void method is a method that does not return any value. When you declare a method as void, it indicates that the method performs a task or a set of operations, but it does not produce a result that needs to be returned to the caller. void methods are used when you want to perform actions like printing output, modifying object states, or executing a sequence of statements without returning a specific value.
Here's the basic structure of a void method:
public static void MethodName(parameters) {
// Code to be executed
}Challenge
EasyCreate a void method named PrintNTimes. This method should take two arguments:
- A string
message. - An integer
n.
The method should print the message to the console n times. Use a for loop to repeat the printing.
In the Main method, call PrintNTimes with the inputs message and the input n
Cheat sheet
A void method performs actions without returning a value:
public static void MethodName(parameters) {
// Code to be executed
}Use void methods for tasks like printing output, modifying object states, or executing operations that don't need to return a result.
Try it yourself
using System;
public class Program {
public static void PrintNTimes(string message, int n) {
// Write your code here
}
public static void Main(string[] args) {
string msg = Console.ReadLine();
int n = int.Parse(Console.ReadLine());
PrintNTimes(msg, n);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic Shortcuts10Methods (Functions)
Declaring MethodsMethod ParametersReturn TypesOptional ParametersRecap - Validation FunctionVoid Methods5Operators Part 2
Comparison OperatorsLogical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3