Week_4
Week_4
6. Introduction to Properties in C#
Properties look like fields but work like methods (getters and setters).
csharp
class Student {
public string Name; // Direct field access (Not recommended)
}
With Properties (Encapsulation - Good Practice):
csharp
class Student {
private string name; // Private field
public string Name { // Property
get { return name; }
set { name = value; }
}
}
7. Types of Properties in C#
1. Read-Write Property
csharp
class Person {
private int age;
public int Age {
get { return age; }
set { age = value; }
}
}
2. Read-Only Property
csharp
class Car {
private string model = "Tesla Model 3";
public string Model {
get { return model; }
}
}
3. Write-Only Property
csharp
class Secret {
private string password;
public string Password {
set { password = value; }
}
}
csharp
class Employee {
public string Name { get; set; } // No need to define a private field!
}
• protected internal – Accessible within the same assembly and derived classes.
• private protected – Accessible within the containing class and derived classes within the
same assembly.
csharp
class BankAccount {
private double balance;
public double Balance {
get { return balance; } // Returns balance
set {
if (value >= 0) balance = value; // Ensures no negative balance
}
}
}
4. Indexers in C#
What is an Indexer?
Example of an Indexer
csharp
class Team {
private string[] players = new string[3];
public string this[int index] {
get { return players[index]; } // Access
set { players[index] = value; } // Assign
}
csharp
class Team {
private string[] players = new string[3];
public string this[int index] {
get { return players[index]; } // Access
set { players[index] = value; } // Assign
}
}
csharp
class Team {
private string[] players = new string[3];
public string this[int index] {
get { return players[index]; } // Access
set { players[index] = value; } // Assign
}
}
csharp
Team t = new Team();
t[0] = "Alice"; // Using indexer like an array
Console.WriteLine(t[0]); // Output: Alice
Properties: Used in banking systems, employee management, and e-commerce platforms for
Indexers: Found in databases, collections, and game development to manage multiple values
efficiently.
What is a delegate?
A delegate in C# is a type that holds a reference to a method. It allows methods to be passed as
parameters and called dynamically.