Very good explanation regarding interfaces given by several experts. I voted 5 to most of the solutions.
Just I want to add that with the introduction of
Extension
methods, lot of utility can be availed by using interfaces. Particularly
LINQ
uses heavily, extension methods defined for
IEnumerable
interface, which makes it possible to bring about a common functionality among widely varying types.
[Edit]To clarify my point, here is a small example[/edit]
void Main()
{
Person person = new Person("Person1","North Avenue","New City");
Manager manager = new Manager("Manager","South Avenue","Old City", "Central Area");
Company company1 = new Company("Fast Couriers","East Avenue","City Extension","Courier");
Console.WriteLine ("---------");
Console.WriteLine (person.GetAddressLabel());
Console.WriteLine ("---------");
Console.WriteLine (manager.GetAddressLabel());
Console.WriteLine ("---------");
Console.WriteLine (company1.GetAddressLabel());
}
class Person : IAddress {
public string Name {get; set;}
public string Street {get; set;}
public string City {get; set;}
public Person (string name, string street, string city){
Name = name;
Street=street;
City=city;
}
}
class Manager : Person {
public string AreaManaged {get; set;}
public Manager(string name, string street, string city, string areaManaged) :
base(name,street,city){
AreaManaged = areaManaged;
}
}
class Company : IAddress {
public string BusinessType {get; set;}
public string Name {get; set;}
public string Street {get; set;}
public string City {get; set;}
public Company (string name, string street, string city, string businessType){
Name = name;
Street=street;
City=city;
BusinessType = businessType;
}
}
interface IAddress
{
string Name {get; set;}
string Street {get; set;}
string City {get; set;}
}
static class ExtensionMethods {
static public string GetAddressLabel(this IAddress address){
return string.Format("{0}\n{1}\n{2}",
address.Name,address.Street,address.City);
}
}