Indexers and Properties in C#
What are Properties in C#?
Properties in C# are special members of a class that provide a flexible mechanism to read, write, or compute the values of private fields. They encapsulate data and help in data validation.
Key Features of Properties
- Encapsulates fields with controlled access.
- Provides get and set accessors.
- Supports auto-implemented properties for cleaner code.
- Allows property validation inside
set
accessor.
Example: Defining and Using Properties
The following example demonstrates how to declare and use properties in C#.
Example: Properties in C#
public class Person
{
private string name;
private int age;
public string Name
{
get { return name; }
set { name = value; }
}
public int Age
{
get { return age; }
set
{
if (value > 0)
age = value;
else
Console.WriteLine("Age must be positive.");
}
}
}
// Usage
class Program
{
static void Main()
{
Person person = new Person();
person.Name = "Alice";
person.Age = 25;
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}
// Output:
// Name: Alice, Age: 25
The Name
and Age
properties control access to private fields, enforcing data validation.
Auto-Implemented Properties
C# provides auto-implemented properties for simpler code when no additional logic is needed.
Example: Auto-Implemented Properties
public class Employee
{
public string Name { get; set; }
public int Salary { get; set; }
}
// Usage
Employee emp = new Employee { Name = "John", Salary = 50000 };
Console.WriteLine($"Employee: {emp.Name}, Salary: {emp.Salary}");
// Output:
// Employee: John, Salary: 50000
The Name
and Salary
properties are automatically managed by C# without explicit fields.
What are Indexers in C#?
Indexers allow instances of a class to be accessed like an array. They provide a way to create classes that behave like collections.
Key Features of Indexers
- Allows objects to be accessed like an array.
- Uses the
this
keyword. - Supports multiple parameters for multi-dimensional indexing.
- Useful for implementing collections.
Example: Defining and Using Indexers
The following example demonstrates how to define and use an indexer in C#.
Example: Indexers in C#
using System;
public class StudentCollection
{
private string[] students = new string[3];
public string this[int index]
{
get { return students[index]; }
set { students[index] = value; }
}
}
// Usage
class Program
{
static void Main()
{
StudentCollection studentList = new StudentCollection();
studentList[0] = "Alice";
studentList[1] = "Bob";
studentList[2] = "Charlie";
Console.WriteLine(studentList[1]); // Output: Bob
}
}
Here, StudentCollection
allows access to student names using array-like indexing.
When to Use Properties and Indexers?
- Use properties for encapsulating fields with controlled access.
- Use auto-implemented properties when no additional logic is needed.
- Use indexers when creating classes that behave like collections.