C# Method Parameters
Passing data to methods.
C# Parameters and Arguments
Information can be passed to methods as parameter. Parameters act as variables inside the method.
Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.
Syntax
void MyMethod(string fname)
{
Console.WriteLine(fname + " Refsnes");
}
Return Values
The void keyword, used in the previous examples, 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, etc.) instead of void, and use the return keyword inside the method:
Examples
Method Parameters
Passing a string name.
using System;
class Program
{
static void MyMethod(string fname)
{
Console.WriteLine(fname + " Refsnes");
}
static void Main(string[] args)
{
MyMethod("Liam");
MyMethod("Jenny");
MyMethod("Anja");
}
}Multiple Parameters
Passing name and age.
using System;
class Program
{
static void MyMethod(string fname, int age)
{
Console.WriteLine(fname + " is " + age);
}
static void Main(string[] args)
{
MyMethod("Liam", 5);
MyMethod("Jenny", 8);
}
}Return Values
Returning an integer.
using System;
class Program
{
static int MyMethod(int x)
{
return 5 + x;
}
static void Main(string[] args)
{
Console.WriteLine(MyMethod(3));
}
}