7 Things About C#: Methods

Learn how to avoid code duplication and modularize code with C# Methods.

Joe Mayo

--

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
}

--

--

No responses yet