Monday, June 7, 2010

Static members in C#


using System;


using System.Collections.Generic;


using System.Linq;


using System.Text;


 


namespace Test_in_cs


{


    //Class for demonstration of static member.


    class staticdemo


    {


        private static int count;


        private int info;


        public staticdemo()//Constructor.


        {


            count++;//Static member increments with every instantiation.


        }


        public static void num()//Static method.


        {


            Console.WriteLine("Number of objects is: " + count);


        }


        public int setter(int a)


        {


            info = a;


            return info;


        }


    }


    class Program


    {


        static void Main(string[] args)


        {


            Console.Write("Enter the number of objects to be created: ");


            String s = Console.ReadLine();


            int n = int.Parse(s);


            staticdemo[] obj = new staticdemo[n];//Only memory allocation.


            staticdemo.num();


            for (int i = 0; i < n; i++)


            {


                obj[i] = new staticdemo();//Actual instantiation.


                Console.Write("Information in object " + (i+1));


                Console.WriteLine("is " + obj[i].setter(i + 1));


            }


            staticdemo.num();


        }


    }


}

No comments:

Post a Comment