C# Simplified, part 2: Methods & Programming Constructs - Declaring methods with parameters
(Page 2 of 6 )
As explained earlier, you can declare methods with parameters. You can supply any number of parameters inside a method. The parameter should include a valid data type followed by a variable, as shown in listing 2.3.
Listing 2.3
void display(int x, int y)
{
//Statements goes here
}
An important point which you must keep in mind is that you have to supply relevant values while calling the method, as shown in listing 2.4. Otherwise, there will be compilation errors.
Listing 2.4
d.display(200,400);
The listing given below illustrates this concept with a help of a simple program.
Listing 2.5
using System;
class Params
{
// A Method named display() declared with two parameters x and y of type integer
void display(int x,int y)
{
Console.WriteLine(x);
Console.WriteLine(y);
}
public static void Main()
{
//Object of the class created
Params prm = new Params();
//Method display() called by passing two integer values
prm.display(700,900);
}
}
In the above listing, a method named display() is declared with two integer parameters. The method also gives necessary statements for printing the value of those variables. Note that we haven't given any value to the variables while declaring the method. Inside the Main() method, an object of the class is created, and the method display() is called by passing two values. If you are not passing any values while accessing the method, there will be compilation errors.
Next: Overloading Methods >>
More C# Articles
More By Anand Narayanaswamy