1: Sample Code for Interface:
using System;
interface IShuttle
{
void Register(string empName);
void UnRegister(string empName);
}
class Employee
{
private int empId;
private string empName;
public Employee(int empId, string empName)
{
this.empId = empId;
this.empName = empName;
}
public int EmpId
{
get { return empId; }
}
public string EmpName
{
get { return empName; }
}
}
class Participant : Employee, IShuttle
{
public Participant(int empId, string empName)
: base(empId, empName)
{}
//illustration of interface
public void Register(string empName)
{
Console.WriteLine("Congratulations " + empName + " you have been
successfully registered to use Shuttle");
}
public void UnRegister(string empName)
{
Console.WriteLine(empName + " you have been successfully deregistered
from using Shuttle ");
}
}
class MainClass
{
public static void Main()
{
Participant part1 = new Participant(101, "Jane");
IShuttle shutObj = part1;
shutObj.Register(part1.EmpName);
shutObj.UnRegister(part1.EmpName);
}
}
Output:
2: Sample Implementation for Explicit Interface:
using System;
interface IShuttle
{
void Register(string empName);
void UnRegister(string empName);
}
/*Consider another interface Called as IMealCoupon which provides fuctionality
to Register and Deregister for the Meal coupon
* */
interface IMealCoupon
{
void Register(string empName);
void UnRegister(string empName);
}
class Employee
{
private int empId;
private string empName;
public Employee(int empId, string empName)
{
this.empId = empId;
this.empName = empName;
}
public int EmpId
{
get { return empId; }
}
public string EmpName
{
get { return empName; }
}
/*
Participant can register for both meal and shuttle, leads to conflict as Register
and De-Register is present in Interface IShuttle and IMealCoupon.
This can be resolved using Explicit Interfaces:
* */
class Participant : Employee, IShuttle, IMealCoupon
{
public Participant(int empId, string empName)
: base(empId, empName)
{
void IShuttle.Register(string empName)
{
Console.WriteLine("Congratulations " + empName + " You have been
successfully registered for shuttle");
}
void IShuttle.UnRegister(string empName)
{
Console.WriteLine(empName + " You have been successfully deregistered
from using shuttle");
}
void IMealCoupon.Register(string empName)
{
Console.WriteLine("Congratulations " + empName + " you have been
successfully registered to use Meal Coupon");
}
void IMealCoupon.UnRegister(string empName)
{
Console.WriteLine(empName + " you have been successfully deregistered
from using Meal Coupon");
}
}
class MainClass
{
static void Main(string[] args)
{
Participant participantp1 = new Participant(101, "Jane");
IShuttle shutObj = participantp1;
shutObj.Register(participantp1.EmpName);
shutObj.UnRegister(participantp1.EmpName);
IMealCoupon mealObj = participantp1;
mealObj.Register(participantp1.EmpName);
mealObj.UnRegister(participantp1.EmpName);
}
}