A method is a collection of statements that perform some specific task and return result to the caller. A method can perform some specific task without returning anything. Methods allow us to reuse the code without retyping the code.
Methods are useful because they let us use the same block of statements at many points in the program. However, they become more useful if we allow them to have parameters.
A parameter is a means of passing a value into a method call. The method is given the data to work on. As an example, consider the code below:
Example 1:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class Program { static void print(int i) { Console.WriteLine("i is : " + i); } static void Main(string[] args) { print(19); Console.ReadKey(); } } |
Output:
Examples 2: Below is a simple example of a method that calculates rectangle’s area:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
static double GetRectangleArea(double width, double height) { double area = width * height; return area; } static void Main(string[] args) { int w, h; Console.Write("Width : "); w = Convert.ToInt32(Console.ReadLine()); Console.Write("Height : "); h = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Area of Rectangle : "+GetRectangleArea(w, h)); Console.ReadKey(); } |
Output:
Example 3:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
static void PrintLogo() { // Method's body starts here Console.WriteLine("www.csharp-console-examples.com"); } // … And finishes here static void Main(string[] args) { PrintLogo(); Console.ReadKey(); } |
Output:
Examples 4:
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
static void PrintLogo(string logo) { Console.WriteLine(logo); } static void Main(string[] args) { PrintLogo("Methods in C#"); Console.ReadKey(); } |
Output:
Examples 5: Method to Calculate the Sum of Prices of Books
Code:
1 2 3 4 5 6 7 8 9 10 11 12 |
static void PrintTotalAmountForBooks(decimal[] prices) { decimal totalAmount = 0; foreach (decimal singleBookPrice in prices) { totalAmount += singleBookPrice; } Console.WriteLine("The total amount for all books is:" + totalAmount); } |
Exapmles 6: Method to Show whether a Number is Positive.
To clarify the way method execution depends upon its input let’s take look at another example. The method gets as input a number of type int, and according to it returns to the console “Positive“, “Negative” or “Zero“:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
static void PrintSign(int number) { if (number > 0) { Console.WriteLine(number+": Positive"); } else if (number < 0) { Console.WriteLine(number + ": Negative"); } else { Console.WriteLine(number + ": Zero"); } } static void Main(string[] args) { PrintSign(5); PrintSign(0); PrintSign(-9); Console.ReadKey(); } |
Output: