c sharp Logo

C# Class Member


Class Members

Class members are the fundamental building blocks of a class in C#. They represent the data and behavior associated with that class, enabling the creation of structured and reusable code. Class members can be categorized into three main types:

Fields: Fields are variables declared within a class, representing the data or state of an object. They can be of any data type, such as integers, strings, or objects of other classes. Fields are typically declared with access modifiers like public, private, or protected, controlling their visibility and accessibility.

Properties: Properties are a special type of class member that encapsulates the access to fields. They provide a structured and controlled way to access and modify the data of an object, ensuring data integrity and promoting code readability. Properties can have getter and setter methods, allowing controlled access to the underlying fields.

Methods: Methods are blocks of code that define the behavior of an object. They can perform operations, manipulate data, and interact with other objects. Methods are declared with a signature, including the method name, return type, parameters (if any), and access modifiers.

Example: Employee Class

Consider an Employee class:

class Employee {

  // Fields

  private string name;

  private int id;

  private double salary;

 

  // Properties

  public

 string Name {

    get { return name; }

    set { name = value; }

  }

 

  public

 int Id {

    get { return id; }

    set { id = value; }

  }

 

  public

 double Salary {

    get { return salary; }

    set { salary = value; }

  }

 

  // Methods

  public void PrintEmployeeDetails() {

    Console.WriteLine("Employee Name: " + name);

    Console.WriteLine("Employee ID: " + id);

    Console.WriteLine("Employee Salary: " + salary);

  }

 

  public void IncreaseSalary(double percentage) {

    salary *= (1 + percentage / 100);

  }

}

 

This class defines fields for employee name, ID, and salary, along with properties to access and modify these fields. It also includes methods to print employee details and increase the employee's salary.

Creating and Using Objects

Objects are created using the new keyword followed by the class name and parentheses. Once an object is created, its members can be accessed using the dot notation:

Employee employee1 = new Employee();

employee1.Name = "John Doe";

employee1.Id = 12345;

employee1.Salary = 50000.00;

 

employee1.IncreaseSalary(10.00);

employee1.PrintEmployeeDetails();

 

Conclusion

Class members are the essential components of a class in C#, enabling the creation of structured, reusable, and maintainable code. Fields, properties, and methods work together to define the data and behavior of objects, allowing programmers to model real-world entities and their interactions effectively. Understanding class members is crucial for developing effective C# applications.