Functions – Methods with Parameters in CSharp
Methods with Parameters in CSharp
Again: A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method. So whenever a function was declared having one or more paramaters, we need to hand over the same amount of arguments to it (also they need to be from the same data type). If the brackets of the method declaration are empty, we mustn’t use any arguments when calling the method.
Example for a method with parameters – a real life example
A Car is owned by one person, so it is private. When the person wants to use the car, he has to call the following function:
private exhaust useMrBsCar(typeOfFuel myFuel , location a, location b){ // drive from a to b, start the air con, and calculate the amount of exhaust produced based on distance and typeOfFuel return exhaustAmount }
Method in CSharp
In this case the exhaustAmount is being returned. That amount was calculated within the method itself. In order to call the method we could use the following code. useMrBsCar(diesel, New York, Montreal).
When declaring a method, it is important that the method is declared outside of any other function but within a class.
Let have a look at an easier example for a method with a parameter:
public static void writeText(String myText){ Console.WriteLine(myText); Console.ReadLine(); }
This function will write the text we give as an argument to the console. So if I want to write the text “Hello World” to the console I would use the following code now: writeText(“Hello World”); Hereby our arguement is “Hello World”. Even though there is a difference between arguement and parameter, it is often ignored.