6/01/2010

C# Static Members



Static members:
================

1) Static variables:
====================
 Only one copy of static variable is created and it can be shared by any number of objects.
 The default initial value for a static variable is zero (0).

2) Static method:
=================
 Static method can only can only access the static variable.
 To access static method, it must be invoked through class name.

Syntax:
-------  class_name.static_method_name();

Example
-------  enroll.count(); 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StaticMembers
{
    class enroll
    {
        public string name, course;
        public static int k;//Static variable
        public enroll(string n,string c)
        {
            name = n;
            course = c;
            k++;
        }
        public static void count()//Static method
        {
            Console.WriteLine("Total number of students: " + k);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            enroll.count();
            enroll e1 = new enroll("Kamran", "BCA");
            enroll e2 = new enroll("Keyvan", "Msc");
            enroll.count();

            Console.WriteLine("--------------------");
            Console.WriteLine("Name \t Course");
            Console.WriteLine(e1.name + "\t" + e1.course);
            Console.WriteLine(e2.name + "\t" + e2.course);
            Console.WriteLine("--------------------");
        }
    }
}

No comments:

Post a Comment