Stack Overflow GitHub RSS Feed

Byte-sized C# Programming: Methods

Published: November 27, 2018

Let’s continue the example project from the previous post. Towards the end we created a variable employeesMonthlyAverage that was meant to store the monthly average value of how many miles an employee traveled over the last year. We discussed how we would assign a value to that variable, but no where did we mention where that value came from. So…

At a high level, methods can be likened to the steps of an assembly line. I’ve been on a number of factory tours and in them have seen a number of assembly lines. Let’s think about an assembly line at a brewery. At the beginning of the line, a stack of bottles are provided to the line as well as a beverage, some labels and some caps. There are a number of steps it passes through on the line. The bottle has to be rinsed. The bottle is filled with the liquid. The label is glued on. The cap is stamped on. It goes through the line, until it reaches the end where the case of beer emerges. The assembly line doesn’t care if the bottles are green, brown or clear. It doesn’t matter if the beverage is a lager, stout or a soda. It performs the same steps in the same order again and again to produce the case of filled bottles.

A method allows a developer to create an ordered set of instructions for a computer to run. Similar to the assembly line’s instructions, the method’s instructions will perform the same steps in the same order every time the method is run. At the end of the day, the whole point of programming is to create something that will allow a computer to do certain tasks so that a person doesn’t have to do it. A method is one of the core building blocks enabling that.

This sounds exciting! How do I get started?

The first order of business is to know how to define a method. One definition for the word define is: “mark out the boundary or limits of”. That seems to be a pretty accurate definition for what it means to define a method. In order to define a method, we need to answer(at a minimum) these three questions:

  1. What external information needs to be given to the method in order for it to run its set of instructions? This can be likened to the raw materials provided to the assembly line at the beginning of the line.
  2. What name do we want to use to refer to this method?
  3. What type of result is returned from the method? This can be likened to the case that emerged from the end of the assembly line.

In answering these questions, we can understand the boundaries and/or limits of our method.

Uh, I think this makes sense, but how do we accomplish this in practice?

Great question! Let’s look at the question we started with. Where does the value for employeesMonthlyAverage come from in our program? Currently, the user has to make the calculation and assign that value to the variable. This is something a computer should be doing so let’s see how we would make a method for this instead.

First, let’s answer the questions presented above.

  1. In order for the method to calculate the monthly average for a given employee it needs to be given the total number of miles an employee has traveled and the total number of months they have worked this year.
  2. This is mostly arbitrary though it does need to follow a few rules which, for all intents and purposes, are the same as those for variables. To recap(not an exhaustive list), the name can’t have a space, apostrophe or a dash in it. In this instance, CalculateEmployeesMonthlyAverage seems appropriate, so that’s what we’ll use.
  3. The whole point of the method is to calculate the average, so that is what it will return. If you look at the previous post, we determined that the average should be of type decimal, so that is the type of the returned result.

Great, but all of this was the preparation, right? How do we actually program our function?

As a word of warning, while we’ve discussed the problem above in the order I generally tend to think about problems, from start to finish, the definition of a function is done in reverse.

Our function would be defined as follows:

1
decimal CalculateEmployeesMonthlyAverage(int employeesMileage, int monthsEmployed) {}

The decimal at the beginning is stating that a decimal value will be returned from the method. It is similar to saying a case of filled bottles will be returned from the assembly line. After that you see the name we decided on above. Ignoring the (, ), { and } for now, we can see that the other two items presented here are the ones we stated above were “external information to be given to the method in order for it to run its set of instructions”. In order for the method to compute the average it needs to be given the employee’s total mileage for the given year and the number of months they were employed during the year. Just like the assembly line needs to be given bottles, a beverage, labels and caps in order to produce the case.

Thanks for the explanation. This is starting to make sense, but what are the other symbols and what do they do?

That is a great question and is something that definitely takes some getting used to. Just as there are rules about names given in our program, there are other specifications that need to be met for a given program to be valid. These specifications are called syntax. In our discussion of variables, we glossed over the fact that every line we wrote had to end with ;. This is ‘syntax’ that defines the end of a statement, without which our program would be invalid.

Likewise, (, ), { and } are symbols used to signify certain things in our code. In the example of our method so far, the parentheses perform two functions.

  1. It declares the function’s external boundary, as we have discussed, where it advertises what information it needs to perform it’s function and what type each piece of information must be. This will make more sense when we discuss how to use the method in our code.
  2. In addition, it is declaring variables available to the function as we will demonstrate shortly.

Brackets group together the set of instructions the method will run.

I’m going to be honest. Some of this makes sense, but my eyes are starting to glaze a bit. Can we get back to the example?

Sure, we’ll throw down some more code with a bit of explanation and see if it helps clarify everything. First let’s complete our example method by ‘implementing’ it. That means, let’s add the instructions to it.

1
2
3
4
decimal CalculateEmployeesMonthlyAverage(int employeesMileage, int monthsEmployed)
{
  return employeesMileage / monthsEmployed;
}

(Technically speaking, the code above won’t do what we expect it to. It is fine for now though to discuss method syntax. We can understand the technicalities later and fix it then.)

Hopefully the code is pretty readable as is. Just to elucidate it a bit though. return is another piece of syntax. It is a “reserved keyword”. That means a couple of things in C# land. It is given special meaning and it can’t be used as a name. return’s special meaning is that it is used to signify an explicit end to a method. In this case, it is also used to signify what value is going to be returned from the method, namely the value that is the result of dividing employeesMileage by monthsEmployed. Hopefully one can see the resemblance to the assembly line as well. The method is stating: “Give me an employee’s mileage and month’s employed and I will give you back the employee’s monthly average.”.

OK, very nice. I still don’t know how to use the method though. It seems like we have the pieces in place, but how do I actually get it to calculate an average for me?

The way to ‘invoke’ our method is as follows: decimal employeesMonthlyAverage = CalculateEmployeesMonthlyAverage(15013, 6);. This says, run the CalculateEmployeesMonthlyAverage code provided that the value 15013 is the employee’s mileage for the year and 6 is the number of months they worked this year. Store the value that gets returned from that method into the space reserved by the variable employeesMonthlyAverage. The code is calling the method with ‘hard-coded’ values as it is passing 15013 and 6 into the method as would be done in a calculator. The method can also accept variables assuming that their types match those of the method declaration.

To demonstrate, our code above could also look as follows:

1
2
3
int employeesMileage = 15013;
int monthsEmployed = 6;
decimal employeesMonthlyAverage = CalculateEmployeesMonthlyAverage(employeesMileage, monthsEmployed);

The values passed to the method are assigned to the variables of the method in order, so don’t make a mistake and assume that the names of the variables are what is used. Calling the method like: decimal employeesMonthlyAverage = CalculateEmployeesMonthlyAverage(monthsEmployed, employeesMileage); will produce an entirely different result as it will perform the calculation 6/15013 instead of 15013/6.

Now we know where our average value comes from and have explored another of the core building blocks of software development.

Once again, Nice Work!!!

As an eager-to-get-started-developer, while following along, you might have opened up Notepad or Word and typed in the code we have discussed hoping to create your first program. If so, you would have been pretty disappointed. What comes next? How is this supposed to run on the computer?

Those are all valid questions and the real answer is that you need more information before you can start to create a real program. At the end of the next article, we should be able to actually create our first full program.

Stay tuned.