C#.NET : Static Member

Types of Class Members

  1. Non-static Members :

    • This is the default type for all the members.
    • If you are not using "static" keyword while the declaration of a field / property or a method, then it can be called as "Non-static member".
    • The main feature of non-static member is - it will be bounded with the object only.
      1. Non-static Fields / Properties : The memory will be allocated, when an object is created.
      2. Non-static Methods : These methods can implement operations on non-static fields and properties.
  2. Static Members :

    • If you are using "static" keyword while the declaration of a field / property or a method, then it can be called as "Static member".
    • The main feature of non-static member is - it will not be bounded with the any object. It is individually accessible with the class name. In other words, the static members are accessible directly, without even creating one object also.
      1. Static Fields / Properties : The memory will be allocated individually, without any relation with the object.
      2. Static Methods : These methods can implement operations on static fields and properties only; and can‘t access the non-static members
static member

Demo on Static Member


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StaticMembersDemo
{
 class Student
 {
  //non-static data members
  public string StudentName;
  public string Course;
  //non-static methods
 public void SetStudentDetails(string StuName, string Cou)
 {
   StudentName = StuName;
   Course = Cou;
 }
 public void DisplayStudentDetails()
 {
   Console.WriteLine(StudentName + " - " + Course);
 }
 //static data members
 public static string CollegeName = "ABC College of Technology";
 public static string CollegeAddress = "Hyderabad";
 //static methods
 public static void DisplayCollegeDetails()
 {
  Console.WriteLine(CollegeName);
  Console.WriteLine(CollegeAddress);
 }
}

class Program
 {
  static void Main(string[] args)
  {
   //access static members
    Student.DisplayCollegeDetails();
   //access non-static members
    Console.WriteLine();
    Student s1 = new Student();
    Student s2 = new Student();
    s1.SetStudentDetails("Sarath", "MCA");
    s2.SetStudentDetails("Syam", "MBA");
    s1.DisplayStudentDetails();
    s2.DisplayStudentDetails();
    Console.Read();
  }
 }
}

Post a Comment

0 Comments