C# Methods: Parameters, Calls and Return Values
- Get link
- X
- Other Apps
A C# method groups statements under a name so you can call them again. This lesson builds a console program that displays two course messages and calculates a total. Start with our C# Hello World setup guide if you have not created a console project.
Complete method-calling example
Replace Program.cs in a console project with the code below, save it, and run dotnet run from the project directory.
using System;
class Program
{
static void Main()
{
ShowMessage("Welcome to C#");
ShowMessage("Practice one method at a time");
int total = AddLessons(3, 2);
Console.WriteLine($"Total lessons: {total}");
}
static void ShowMessage(string message)
{
Console.WriteLine(message);
}
static int AddLessons(int completed, int planned)
{
return completed + planned;
}
}Expected output
Welcome to C#
Practice one method at a time
Total lessons: 5Main runs first. It calls ShowMessage with a string argument. Execution moves into ShowMessage, prints that string, and returns to the next statement in Main. The second call uses the same method with different data. Defining a method does not run it; a call is required.
Parameters and arguments
message is a parameter: the name used inside the method definition. "Welcome to C#" is an argument: the actual value supplied by the caller. A string parameter accepts text. AddLessons has two integer parameters, so the example supplies two whole numbers in the declared order.
Void versus a return value
ShowMessage has return type void: it performs an action without giving a value back. AddLessons returns an int, which Main stores in total. A return statement ends that method call and sends the result to the caller. Printing a number and returning a number are different operations.
Why static appears here
These methods are static because this introductory example calls them from static Main without constructing an object. Instance methods belong to an object and are useful in later object-oriented exercises. Keep the helpers inside Program, at the same brace level as Main.
Practice and debug
- Change the two messages and confirm their order in the output.
- Call AddLessons with 4 and 0. Predict the result before running.
- Add a method named DoubleLessons that takes one int and returns twice its value.
- Remove one ShowMessage call. Observe that the definition remains but that message is no longer printed.
If a name is not found, check spelling and capitalization. If an argument cannot convert to int, supply a number rather than quoted text. If braces are mismatched, check that each method is inside the class and outside the other methods.
Original video lesson
Further reading
See Microsoft's C# methods guide for signatures, access modifiers, and additional examples.
- Get link
- X
- Other Apps
Comments
Post a Comment