Information can be passed to methods as parameters. Parameters act as variables inside the method.
They are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.
While these terms are often used interchangeably, there is a slight technical difference:
using System;namespace MyApplication { class Program { // 'fname' is a parameter static void MyMethod(string fname) { Console.WriteLine(fname + " Refsnes"); } static void Main(string[] args) { // "Liam", "Jenny", and "Anja" are arguments MyMethod("Liam"); MyMethod("Jenny"); MyMethod("Anja"); } } }
When the method is called, we pass along a first name, which is used inside the method to print the full name.
You can have as many parameters as you like. You just need to separate them with a comma. Just remember that when you call the method, you must pass arguments in the exact same order as the parameters are defined.
using System;namespace MyApplication { class Program { static void MyMethod(string fname, int age) { Console.WriteLine(fname + " is " + age + " years old."); } static void Main(string[] args) { MyMethod("Liam", 5); MyMethod("Jenny", 8); MyMethod("Anja", 31); } } }
Notice that the first argument is a string and the second is an int. If you try to pass an int first and a string second, you will get a compiler error!
You can also use a default parameter value, by using the equals sign (=).
If we call the method without an argument, it uses the default value. These are also known as optional parameters.
using System;namespace MyApplication { class Program { static void MyMethod(string country = "Norway") { Console.WriteLine("I am from " + country); } static void Main(string[] args) { MyMethod("Sweden"); MyMethod("India"); MyMethod(); // Will use the default value "Norway" MyMethod("USA"); } } }
Important: Optional parameters must appear after all required parameters in the method signature. You cannot have a required parameter after an optional one.
In the previous examples, we used the void keyword in all methods. This indicates that the method should not return a value.
If you want the method to return a value, you can use a primitive data type (such as int, double, string, etc.) instead of void, and use the return keyword inside the method.
using System;namespace MyApplication { class Program { static int AddNumbers(int x, int y) { return x + y; } static void Main(string[] args) { int result = AddNumbers(5, 3); Console.WriteLine(result); // Outputs 8 } } }
You can also skip the variable and return the output directly into Console.WriteLine:
Console.WriteLine(AddNumbers(5, 3));
Which keyword is used to return a value from a method?