C# Tutorials
C# Methods
C# Classes
C# Examples
Information can be transmitted along paths as a parameter. The parameters act as a variable within the method.
Specified after the name of the path, inside brackets. You can add as many parameters as you want, just split them into commas.
The following example has a method that takes a string called a fname as a parameter. When the path is called, we transmit the first word, which is used within the path to print the full name:
static void MyMethod(string fname)
{
Console.WriteLine(fname + " Refsnes");
}
static void Main(string[] args)
{
MyMethod("Liam");
MyMethod("Jenny");
MyMethod("Anja");
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
You can also use the default value of the parameter, using the equalizer (=). If we call a route without conflict, it uses the default value ("Norway"):
static void MyMethod(string country = "Norway")
{
Console.WriteLine(country);
}
static void Main(string[] args)
{
MyMethod("Sweden");
MyMethod("India");
MyMethod();
MyMethod("USA");
}
// Sweden
// India
// Norway
// USA
You can have as many parameters as you like:
static void MyMethod(string fname, int age)
{
Console.WriteLine(fname + " is " + age);
}
static void Main(string[] args)
{
MyMethod("Liam", 5);
MyMethod("Jenny", 8);
MyMethod("Anja", 31);
}
// Liam is 5
// Jenny is 8
// Anja is 31
The void keyword, used in the examples above, indicates that the method should not return the value. If you are looking for a way to recover value, you can use the old data type (like int or double) instead of void, and use the return keyword within the method:
static int MyMethod(int x)
{
return 5 + x;
}
static void Main(string[] args)
{
Console.WriteLine(MyMethod(3));
}
// Outputs 8 (5 + 3)
This example returns the sum of two parameters of the method:
static int MyMethod(int x, int y)
{
return x + y;
}
static void Main(string[] args)
{
Console.WriteLine(MyMethod(5, 3));
}
// Outputs 8 (5 + 3)
You can also save the effect to the variable (recommended, as it is easy to read and save):
static int MyMethod(int x, int y)
{
return x + y;
}
static void Main(string[] args)
{
int z = MyMethod(5, 3);
Console.WriteLine(z);
}
// Outputs 8 (5 + 3)
It is also possible to submit arguments by key: value syntax.
Thus, the order of disputes does not matter
static void MyMethod(string child1, string child2, string child3)
{
Console.WriteLine("The youngest child is: " + child3);
}
static void Main(string[] args)
{
MyMethod(child3: "John", child1: "Liam", child2: "Liam");
}
// The youngest child is: John
Named arguments are especially useful if you have many parameters with default values, and you only want to specify one of them when you call it:
static void MyMethod(string child1 = "Liam", string child2 = "Jenny", string child3 = "John")
{
Console.WriteLine(child3);
}
static void Main(string[] args)
{
MyMethod("child3");
}
// John