using System.Collections.Generic;
namespace ExplicitInterfacesSite
{
// Simple interface for Vendor class
public interface IVendor
{
// Return the list of vendor names
List<string> GetData();
}
// Simple interface for customer class
public interface ICustomer
{
// Return the list of customer names.
// This function name is conflicting with IVendor's GetData.
List<string> GetData();
// Another method, which is not conflicti
string GetCustomerAddress(int customerId);
}
}
using System.Collections.Generic;
namespace ExplicitInterfacesSite
{
public class CompanyDAL : IVendor, ICustomer
{
#region IVendor Members
List<string> IVendor.GetData()
{
// Implement your logic to get the list of Vendor Names
return new List<string>() {"Vendor1", "Vendor2", "Vendor3"};
}
#endregion
#region ICustomer Members
// This is how we should implement the conflicting method, explicitely
List<string> ICustomer.GetData()
{
// Implement your logic to get the list of Customer Names
return new List<string>() {"Customer1", "Customer2"};
}
// No need of Interface.MethodName as there is no conflict.
public string GetCustomerAddress(int customerId)
{
return "Dummy Customer Address";
}
#endregion
}
}
using System;
using System.Collections.Generic;
namespace ExplicitInterfacesSite
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Create the object
CompanyDAL expliciteObj = new CompanyDAL();
// Can directly call method, whose name is not confliciting
expliciteObj.GetCustomerAddress(1);
// Cast the object to the interface first and then call the conflicting method.
// Here we are calling the GetData() method of IVendor class.
List<string> lstVendors = (expliciteObj as IVendor).GetData();
Response.Write("Vendor List:</br>");
foreach (string vendorName in lstVendors)
{
Response.Write(vendorName);
Response.Write("</br>");
}
// Cast the object to the interface first and then call the conflicting method.
// Here we are calling the GetData() method of ICustomer class.
List<string> lstCustomers = (expliciteObj as ICustomer).GetData();
Response.Write("Customer List:</br> ");
foreach (string customerName in lstCustomers)
{
Response.Write(customerName);
Response.Write("</br>");
}
}
}
}
List<string> lstVendors = (expliciteObj as IVendor).GetData();
I first typecast the expliciteObj to the Interface type, and then called the conflicting method. By doing this we are able to remove the conflict/ambiguity in the method name. This would return a list of string. It should contain below strings (vendor names):
List<string> lstCustomers = (expliciteObj as ICustomer).GetData();
expliciteObj is first converted to ICustomer and then called the method GetData. This call would return a list of customer names. In our case it should be:
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (0)