0% found this document useful (0 votes)
7 views

Week_4

This document provides an overview of properties and indexers in C#, highlighting their importance in encapsulating data and enhancing code readability. It details various types of properties, including read-write, read-only, and write-only properties, as well as auto-implemented properties and their access modifiers. Additionally, it explains the concept of indexers, their use cases, and best practices for utilizing properties and indexers effectively in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Week_4

This document provides an overview of properties and indexers in C#, highlighting their importance in encapsulating data and enhancing code readability. It details various types of properties, including read-write, read-only, and write-only properties, as well as auto-implemented properties and their access modifiers. Additionally, it explains the concept of indexers, their use cases, and best practices for utilizing properties and indexers effectively in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Week_4

By the end of this lecture, students will be able to:

6. Introduction to Properties in C#

What are Properties?

Properties are special methods that control access to class fields.

They provide a way to encapsulate data and ensure controlled access.

Properties look like fields but work like methods (getters and setters).

Example (Using Fields vs. Properties)

Without Properties (Using Public Fields - Bad Practice):

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; }
}
}

Why Use Properties?

Protects data from direct modification.

Allows validation logic (e.g., restricting values).

Improves readability and maintainability.

7. Types of Properties in C#

1. Read-Write Property

Allows both getting and setting the value.

csharp
class Person {
private int age;
public int Age {
get { return age; }
set { age = value; }
}
}
2. Read-Only Property

Can only retrieve data but cannot modify it.

csharp
class Car {
private string model = "Tesla Model 3";
public string Model {
get { return model; }
}
}

3. Write-Only Property

Can only set data but not retrieve it.

csharp
class Secret {
private string password;
public string Password {
set { password = value; }
}
}

Use Case: Storing sensitive data like passwords.

4. Auto-Implemented Properties (Shortcut!)

C# allows a shorthand for simple properties:

csharp
class Employee {
public string Name { get; set; } // No need to define a private field!
}

Benefit: Less code, better readability.

Property Access Modifiers

C# allows different access modifiers on properties:

• public – Accessible from anywhere.

• private – Accessible only within the class.

• protected – Accessible within the class and its derived classes.

• internal – Accessible within the same assembly.

• protected internal – Accessible within the same assembly and derived classes.

• private protected – Accessible within the containing class and derived classes within the
same assembly.

3. Using Get and Set with Logic (Encapsulation)


We can add logic inside get/set to enforce rules.

csharp
class BankAccount {
private double balance;
public double Balance {
get { return balance; } // Returns balance
set {
if (value >= 0) balance = value; // Ensures no negative balance
}
}
}

Why is this important?

Prevents invalid data entry (e.g., negative balances in bank accounts).

Enhances security and reliability.

Activity 1: Think-Pair-Share (10 minutes)

1. Think of a real-world example where properties should be used.

2. Discuss with a partner: Why is a property better than a public field?

3. Share your thoughts with the class.

4. Indexers in C#

What is an Indexer?

Indexers allow objects to be accessed like arrays.

They enable class instances to behave like collections.

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

Why Use Indexers?

Useful for collections and lists.

Makes code more intuitive and readable.

5. Comparison: Properties vs. Indexers

Feature Properties Indexers

Access Uses named properties (e.g., `Person.Name`) Uses index (`object[index]`)

Use Case Encapsulating a single value Accessing multiple values

Example `car.Model` `team[0]`

6. Real-World Applications of Properties & Indexers

Properties: Used in banking systems, employee management, and e-commerce platforms for

controlled access to data.

Indexers: Found in databases, collections, and game development to manage multiple values

efficiently.

7. Best Practices for Using Properties & Indexers

Use properties instead of public fields to maintain encapsulation.

Add validation inside `set` methods to avoid incorrect data entry.

Use indexers when working with collections inside a class.

Avoid unnecessary `set` methods for read-only data.

8. Conclusion & Summary

✔ Properties provide controlled access to fields.

✔ Auto-implemented properties simplify code.

✔ Indexers allow object-based indexing, making classes act like arrays.

✔ Use properties for individual values, and indexers for collections.

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.

Delegates can be categorized into:


Single-Cast Delegate – Points to one method at a time.
Multi-Cast Delegate – Points to multiple methods and calls them sequentially.

You might also like