Monday, February 21, 2011

Methods

Methods are used to make your applications clean or it would be one big code fest. It's also used when you need a piece of code multiple times, so you don't have to copy paste the same piece of code over and over.

Let's begin by creating a new console application called "Methods".


Create the method "private static void ShowHelloWorld(){ }" below your "Main" method. Type in your new method the code "Console.Write("Hello World!");" and "Console.Read();" like you did on your "Hello World" project. This should show the exact same as your old "Hello World" project when you run it by pressing F5 on your keyboard.


A method consists of an access modifier, a modifier (access modifiers are part of modifiers), a return data type and a name (Yes, I did just make "name" bold to give it an extra effect).

An access modifier exists to give your method an access level. There are four access modifiers in C#:
  • Private : The method can only be called within its own class
  • Public : The method can always be called
  • Internal : The method can only be called in its own project
  • Protected : The method can only be called within its own class and classes that are derived from that class
The fact that you can use the "Write" method from the class "Console" means the "Write" method is public. Your method "ShowHelloWorld" is private, so you won't be able to use it outside your "Program" class, because you don't have to in this case.

There are a lot of modifiers: abstract, const, event, extern, override, readonly, sealed, static, unsafe, virtual and volatile. The only reason the method "ShowHelloWorld" is static is because it's being called from a static method "Main". If the method wasn't static, then calling the method "ShowHelloWorld" would be a bit harder, because of the method "Main" being static. The method "Main" is static, because there should be only one. All the modifiers will be discussed at a certain point, but the modifiers will be too much to explain right now.

Methods can return data and the return data type defines what kind of data will be returned. In your method "ShowHelloWorld" the return data type is void, because the method is for showing something and not for returning something.

Naming a method is very important. You should give it a name that describes its functionality.


Imagine that you work at a computer store and your manager wants to calculate the price of a new computer mouse based on the costs of 5 dollars. Your manager tells you that the price is calculated by multiplying the costs by 2, dividing that by 5, adding that up by 2 and then subtracting 2 of that (Your manager isn't very smart). First you'll need a method:
private static int CalculatePrice(int costs)
{

}
You want the method to return the price by calculating the costs and that's why it has a parameter "int costs" which will be 5 dollars in this example and a return basic data type int (int is the basic data type of "price" which we will return). Parameters have a data type, so that means your method "CalculatePrice" won't accept data of the basic data type string "Hello World!" when it has a basic data type int.


Most methods have parameters. The method "Write" of the class "Console" is one of many. When you type "Console.Write(" you will see "Console.Write(bool value)". This means that you can give the "Write" method data of the basic data type bool (true or false) and it will write that for you on the screen. The method "Write" has the return data type void and that means that the method won't return anything. In total there are 18 methods with the name "Write" in the class "Console", but they all have different parameters. This is called method overloading.


You can for example copy paste your "CalculatePrice" method and give it no parameters, more parameters or different parameters. Don't forget that your "costs" variable might not exist if you change the parameters.


Now back to calculating the price. Add the following to your method "CalculatePrice":
int price = 0;
price = costs * 2;
price = price / 5;
price = price + 2;
price = price - 2;
return price;
"int price = 0;" creates a variable that will hold the price. "price = costs * 2" can be looked at as "10 = 5 * 2" which is the same as "5 * 2 = 10". You have to memorise that first the "5 * 2" will be calculated with the outcome of "10". On the next line you'll see "price = price / 5". It looks like this before it's been calculated: "10 = 10 / 5". After calculating it looks like "2 = 2 / 5", but that doesn't matter anymore, because you have your answer, namely "2" and you don't need anything more from that piece of code. The same happens for the rest: "price = price + 2" -> "4 = 2 + 2" and "price = price - 2" -> "2 = 4 - 2". In the end the variable "price" has the data "2", so the method "CalculatePrice" returns the number "2". The "return" keyword makes your application stop executing your method at that point even if it hasn't reached the end of your method yet.

Now you have a "CalculatePrice" method that calculates the price based on the costs. Make use of that method by typing the following in the "Main" method above the method "ShowHelloWorld":
int computerMouseCosts = 5;
int computerMousePrice = CalculatePrice(computerMouseCosts);
Console.Write(computerMousePrice);
"int computerMouseCosts = 5;" is the 5 dollar costs for the computer mouse your manager wants to determine the price on. "int computerMousePrice = CalculatePrice(computerMouseCosts);" is where the "CalculatePrice" method will calculate the price based on the costs of the computer mouse and the price will be returned by the method "CalculatePrice" to the variable "computerMousePrice". The last step is to write the price on your screen by typing "Console.Write(computerMousePrice);". Run your application by typing F5 on your keyboard and it should show "2Hello World!".

You're a good programmer so you were already going to change "Console.Write(computerMousePrice);" to "Console.Write(computerMousePrice + "\n");". Run your application now and you should see "Hello World!" on a new line.

You would've saved yourself from copy pasting your code by using the "CalculatePrice" method if your manager wanted to calculate more prices that are calculated the same way. Too bad that your manager got fired for trying to steal the fire alarm, but you got promoted to manager by showing the higher ups what you've learned so far.

Source Code Methods Project

>> Classes

No comments:

Post a Comment