Member-only story

7 Things About C#: Methods

Joe Mayo
8 min readDec 10, 2024

--

In all of the previous articles of this series, all you needed to do is open an editor and start writing statements and loops. This is fine for practice or a short and quick utility that you might not ever use or update again.

However, the problem with duplicating code is that if you do have to change anything, it will become increasingly difficult to work with over time. For example, what if two different parts of the application used the same code? A change or bug fix in one place would have to be done in the other, or worse, you might forget that the code was duplicated and the bug still remains — only in another location.

That’s where methods come in — they let you write code one time and use it from multiple parts of the application. In other programming languages, methods are called functions, procedures, and sometimes messages. This article explains a few things about C# methods, which largely exist for the same purpose.

1 — Methods have a basic structure

There are 4 primary parts of all methods: return type, name, parameter list, and body. Here’s an example:

void ShowAddress()
{
// code goes here
}

In this example, void is the return type, meaning that this method doesn’t return anything.ShowAddress is the name, which is important for when we want to call this method from other code. The () is a parameter list. Empty parenthesis indicate that the method doesn’t accept parameters. Finally, the body, between opening and closing braces {}, is where you write the code that this method runs when it gets called.

Note: As shown in the previous example for the ShowAddress method, the void keyword is technically not a type, but rather a way to indicate that a method returns nothing.

Here’s a short program that defines and calls a method:

string street = "";
string city = "";
string state = "";
string zip = "";

Console.Write(@"What is your street address?: ");
street = Console.ReadLine();

ShowAddress();

Console.Write(@"What is your city?: ");
city = Console.ReadLine();

ShowAddress();

Console.Write(@"What…

--

--

Joe Mayo
Joe Mayo

Written by Joe Mayo

Author, Instructor, & Independent Consultant. Author of C# Cookbook: — http://bit.ly/CSharpCookbook — @OReillyMedia #ai #csharp #Web3

No responses yet

Write a response