In this tutorial you will learn how to create and use method in C# programming.
Example 1: Write a program to explain method in C#. Create a static function add() that accept two number from user and returns sum of the number.
C# 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 27 28 29 30 31 32 33 34 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Example1 { class calculation { static int num1, num2, result; public static void add() { Console.Write("Enter number 1st.\t"); num1 = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter number 2nd.\t"); num2 = Convert.ToInt32(Console.ReadLine()); result = num1 + num2; Console.Write("\nAdd = {0}", result); Console.ReadLine(); } } class Program { static void Main(string[] args) { calculation.add(); } } } |
Example 2:Example Program Without Parameters & With Return Value Type
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 27 28 29 30 31 32 33 |
// C# program to illustrate Method With // Parameters & Without Return Value Type using System; namespace ConsoleApplication3 { class Geeks { // This method take the side of // the square as a parameter and // after obtaining the result, // it simply print it without // returning anything.. static void perimeter(int p) { // Displaying the perimeter // of the square Console.WriteLine("Perimeter of the Square is " + 4 * p); } // Main Method static void Main(string[] args) { // side of square int p = 5; // Method invoking perimeter(p); } } } |