4.1.1.10–4.1.1.12 - Subroutines, parameters and return values (C#)
Learn how named subroutines divide a program into reusable operations, pass data through a clear interface and return results to their caller.
This C# route is incomplete: runnable support pending. The examples and questions below use native written C#; they do not provide Run.
Procedures and functions
A subroutine is a named, out-of-line block of code: its definition is separate from the statement that calls it. A call transfers control to that block, executes its instructions and then returns control to the caller. C# calls subroutines methods. A method must be declared inside a class; the examples here use static methods in Program so Main can call them directly.
Procedure and function
A procedure performs an operation without returning a result. A function returns a value that its caller can use. In C#, a procedure has return type void; a function declares the type of its returned value.
using System;
class Program
{
static void PrintHeading()
{
Console.WriteLine("Results");
Console.WriteLine("-------");
}
static void Main()
{
PrintHeading();
Console.WriteLine(27);
PrintHeading();
}
}
The first call prints two lines, then execution resumes at Console.WriteLine(27). The second call executes the same definition again. The definition's position in the source does not make it execute automatically; the call does.
Subroutines support decomposition: a large problem becomes smaller named operations. PrintHeading communicates an intention more clearly than repeated printing statements. Reuse reduces duplication, so changing the heading in one definition changes every call. A small subroutine can be tested on its own, and a fault can be isolated to the operation that implements that responsibility. A team can work on different operations once their interfaces are agreed. These benefits depend on sensible boundaries: a huge method that handles every responsibility is still difficult to maintain.
Interfaces and parameters
A method's interface describes how other code uses it: its name, parameter order and types, return type, and any conditions promised by caller or method. This is the interface of a subroutine, rather than the C# interface type used later in object-oriented design.
static int AddDelivery(int itemPence, int deliveryPence)
{
return itemPence + deliveryPence;
}
itemPence and deliveryPence are formal parameters: local names in the definition. In AddDelivery(1250, 300), the arguments supply 1250 and 300 in that order. In AddDelivery(price, charge), the expressions are evaluated and their values supplied. Meaningful types and names help callers avoid mistakes, but C# accepts two reversed int arguments, so the documented order matters.
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account