Lecture Topics:
Lab:
IDisposable
, IComparable
.Interfaces define a contract of methods, properties, events, or indexers that a class or struct must implement. They are essential for achieving abstraction and loose coupling in .NET.
Definition:
Declared with the interface
keyword, typically prefixed with I
(e.g., IEnumerable
).
Example:
public interface IEmployee
{
string Name { get; set; }
void Work();
}
Implementing an Interface:
A class implements an interface by providing implementations for all its members.
Example:
public class Employee : IEmployee
{
public string Name { get; set; }
public void Work() => Console.WriteLine($"{Name} is working");
}
Employee emp = new Employee { Name = "Alice" };
emp.Work(); // Outputs: Alice is working
Explicitly Implementing an Interface:
Explicit implementation binds members to the interface type, not the class, to avoid naming conflicts or hide implementation details.
Example:
public class Employee : IEmployee
{
public string Name { get; set; }
void IEmployee.Work() => Console.WriteLine($"{Name} is explicitly working");
}
Employee emp = new Employee { Name = "Bob" };
// emp.Work(); // Error: Work is not public
((IEmployee)emp).Work(); // Outputs: Bob is explicitly working
Key Points:
Inheritance in Interfaces:
Interfaces can inherit from other interfaces, requiring implementers to provide all members from the base and derived interfaces.
Example:
public interface IPerson
{
string Name { get; set; }
}
public interface IEmployee : IPerson
{
void Work();
}
public class Employee : IEmployee
{
public string Name { get; set; }
public void Work() => Console.WriteLine($"{Name} is working");
}
Default Interface Methods (C# 8.0+):
Introduced in .NET Core 3.0, allow interfaces to provide default implementations.
Example:
public interface IEmployee
{
string Name { get; set; }
void Work();
void TakeBreak() => Console.WriteLine("Taking a break"); // Default implementation
}
public class Employee : IEmployee
{
public string Name { get; set; }
public void Work() => Console.WriteLine($"{Name} is working");
// TakeBreak is inherited automatically
}
Employee emp = new Employee { Name = "Alice" };
emp.TakeBreak(); // Outputs: Taking a break
Key Points:
Key Points:
public
.IEnumerable
, IDisposable
, IComparable
).Why This Matters: