Method in C# with Four Examples

Hi Programmers , welcome to new article of c#.net.This article i’ll write the post for method in c# console application. The Method is a code block that contains a series of statement. The Statement is executed by calling the method.
Syntax :
[access modifier] return type Method_Name ([parameter list])
{
………..
Method Body
……….
}
Let’s see codes of different types of method used in C#

Example 1
Example 2
Example 3
Example 4

Directly Test below codes into Editor

#Without Parameters & Without Return Type
using System;
namespace ConsoleApp1 
{
    class Program 
    {  
        public void sum()
        {
            int a, b, c;
            Console.WriteLine("Enter Two Numbers ");
            a = int.Parse(Console.ReadLine());
            b = int.Parse(Console.ReadLine());
            c = a + b;
            Console.WriteLine("Sum = " + c);
        }
        static void Main(string[] args) 
        {
            Program p = new Program();
            p.sum();
        }
    }
}

****************************
#With Parameters & Without Return Value Type
using System;
namespace ConsoleApp1 
{
    class Program 
    {  
        public void sum(int p,int q)
        {
            Console.WriteLine("Sum = " + (p + q));            
        }
        static void Main(string[] args) 
        {
            Program p = new Program();
            p.sum(12,7);
        }
    }
}

**************************************
#Without Parameters & With Return Value Type
using System;
namespace ConsoleApp1 
{
    class Program 
    {  
        public int sum()
        {
            int a, b, c;
            Console.WriteLine("Enter Two Numbers ");
            a = int.Parse(Console.ReadLine());
            b = int.Parse(Console.ReadLine());
            return (a + b);
        }
        static void Main(string[] args) 
        {
            Program p = new Program();
            int c = p.sum();
            Console.WriteLine("Sum = " + c);
        }
    }
}

***********************
#With Parameters & With Return Value Type
using System;
namespace ConsoleApp1 
{
    class Program 
    {  
        public int sum(int p,int q)
        {
            return (p + q);            
        }
        static void Main(string[] args) 
        {
            Program p = new Program();
            int a, b, c;
            Console.WriteLine("Enter Two Numbers ");
            a = int.Parse(Console.ReadLine());
            b = int.Parse(Console.ReadLine());
            c = p.sum(a, b);
            Console.WriteLine("Sum = " + c);
        }
    }
}

Happy Coding…Thanks.

Post Author: adama