Organizing code into functions

Organizing code into functions

How to:

Imagine you’ve got code that prints a greeting several times. Without functions, it’s a mess. With functions, it’s neat.

// Without functions - repetitive
Console.WriteLine("Hello, Amy!");
Console.WriteLine("Hello, Bob!");
Console.WriteLine("Hello, Charlie!");

// With functions - cleaner
void Greet(string name) {
    Console.WriteLine($"Hello, {name}!");


Output is the same, but the second version is much tidier.

Deep Dive

Way back, in assembly language days, you’d jump to different code spots with GOTO—chaotic and hard to track. Functions are a major level-up, like organized drawers in a toolbox. Alternatives? Sure. You’ve got methods, which are functions in a class context. Then there are lambdas and inline functions for quick, one-off tasks.

About implementation—small, focused functions are gold. They’re easier to test and debug. Large functions with many responsibilities can become monstrous, earning the dubious title “spaghetti code”. Stick to one job per function; you’ll thank yourself later.

See Also

For more on functions and best practices, check out: