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.
Class members are the elements inside a class that define its functionality. They include variables, methods, constructors, properties, and more.
Fields store data inside a class. They represent the state of an object.
class Student
{
public string name;
public int age;
}
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);
}
}
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;
}
}
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; }
}
}
A destructor is used to clean up resources before an object is destroyed.
class Student
{
~Student()
{
Console.WriteLine("Object destroyed");
}
}
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();
}
}
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#.