Monday, July 28, 2014

Static Method in C#

static public int Add(int x, int y)    { 
       int result = x + y;       return result;    }//END   Add
static means that the function is not class instance dependent. So you can call it without needing to create a class instance of Program class.
or you should create in instance of your Program class, and then call Add on this instance. Like so:
 Program prog = new Program()  prog.Add(5,10);
  
Example:

namespace ConsoleApplication2
{
    class Program
    {
        
        static void Main(string[] args)
        {

            Console.WriteLine("Enter operand 1");
            int a = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter operand 2");
            int b = Convert.ToInt32(Console.ReadLine());
            //Program add1 = new Program();
           
           Console.WriteLine(Program.add(a,b)); 
            
        }

        static public int add(int x, int y)
        {
            int c = x + y;
            return c;

        }
    }
}

No comments:

Post a Comment