Calling Method Example in C#

code:

with object creation from class:

using System;

namespace CallingMethods
{
    class Program
    {
       int Add(int a, int b)
       {
           int result;
           result = a + b;
           return result;
       }
        static void Main(string[] args)
        {
            int first, second;
            Console.WriteLine("1st number:");
            first=Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("2nd number");
            second = Convert.ToInt32(Console.ReadLine());
            Program obj1=new Program();
            
            int result = obj1.Add(first, second);
            Console.WriteLine("The addition is: "+result);
            Console.ReadKey();
        }
    }
}

If we don’t want to use object we can use static keyword here:

using System;

namespace CallingMethods
{
    class Program
    {
       static int Add(int a, int b)
       {
           int result;
           result = a + b;
           return result;
       }
        static void Main(string[] args)
        {
            int first, second;
            Console.WriteLine("1st number:");
            first=Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("2nd number");
            second = Convert.ToInt32(Console.ReadLine());
           
            
            int result = Add(first, second);
            Console.WriteLine("The addition is: "+result);
            Console.ReadKey();
        }
    }
}

Static method can be invoked with class name:

using System;

namespace CallingMEthods1
{
    class MyClass
    {
        public static void MyMethod()
        {
            Console.WriteLine("Showing From Method");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyClass.MyMethod();
            Console.ReadKey();
        }
    }
}

Can be invoked without creating objects:

using System;

namespace CallingMEthods1
{
    class Program 
    {
        public static void MyMethod()
        {
            Console.WriteLine("Showing From Method");
        }
    
        static void Main(string[] args)
        {
            MyMethod();
            Console.ReadKey();
        }
    }
}

 

 

 

 

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

Your email address will not be published.