C# Class Members

In C#, a class contains different building blocks called class members. These members define the data and behavior of the class. Class members help structure code in an organized and reusable way.

1. What are Class Members?

Class members are the elements inside a class that define its functionality. They include variables, methods, constructors, properties, and more.

2. Types of Class Members

  • Fields (Variables)
  • Methods
  • Constructors
  • Properties
  • Destructors
  • Indexers
  • Events

3. Fields (Variables)

Fields store data inside a class. They represent the state of an object.


class Student
{
    public string name;
    public int age;
}
    

4. Methods

Methods define the behavior of a class. They perform actions using class data.


class Student
{
    public string name;

    public void Show()
    {
        Console.WriteLine("Name: " + name);
    }
}
    

5. Constructors

Constructors are special methods that are called automatically when an object is created. They are used to initialize class members.


class Student
{
    public string name;

    public Student(string n)
    {
        name = n;
    }
}
    

6. Properties

Properties are a safe way to access private fields using get and set.


class Student
{
    private int age;

    public int Age
    {
        get { return age; }
        set { age = value; }
    }
}
    

7. Destructor

A destructor is used to clean up resources before an object is destroyed.


class Student
{
    ~Student()
    {
        Console.WriteLine("Object destroyed");
    }
}
    

8. Real Example Using Class Members


using System;

class Student
{
    // Field
    public string name;

    // Property
    public int age { get; set; }

    // Constructor
    public Student(string n, int a)
    {
        name = n;
        age = a;
    }

    // Method
    public void ShowInfo()
    {
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}

class Program
{
    static void Main()
    {
        Student s1 = new Student("Rahul", 20);
        s1.ShowInfo();
    }
}
    

9. Key Points

  • Fields: Store data
  • Methods: Perform actions
  • Constructors: Initialize objects
  • Properties: Controlled access to data
  • Destructors: Clean up resources

10. Conclusion

Class members are the core building blocks of any C# class. They define what an object can store and what it can do. Understanding class members is essential for mastering Object-Oriented Programming in C#.

C# Introduction C# Variables & Keywords C# Data Types C# If Else Statement C# Loops C# Comments C# Type Casting C# User Input C# Operators C# Math C# String C# OOP Concepts C# Classes and Objects C# Multiple Classes and Objects C# Class Members C# Constructors C# Access Modifiers