Loading
0x30Lesson 4 of 6

Write methods and use collections

Create reusable methods and process growable lists of values.

15 min 5-question quiz
By the end of this lesson you can
  • Define methods with return values and use List<T> with foreach.

A method names a reusable unit of behavior and can accept parameters and return a value. C# passes int values by value by default, so a method receives a copy. List<T> is a growable standard collection; Add appends values and foreach visits each item. Prefer collection APIs to manually managing memory for ordinary application code.

Program.cs · C# 12
1using System;
2using System.Collections.Generic;
3
4class Program
5{
6    static int Sum(List<int> values)
7    {
8        int total = 0;
9        foreach (int value in values) total += value;
10        return total;
11    }
12}
Output
Sum returns the total of all list elements.

A method signature communicates its input and output types. Generics such as List<int> preserve the element type and let the compiler reject incompatible values before execution.

Key takeaways

  • Methods communicate behavior through parameters and return types.

  • List<T> grows as values are added.

  • foreach is clear when processing each element.

Lesson quiz

5 questions · pass with 4 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Did you like the lesson? 😆👍
Consider a donation to support our work: