C#
//Interface I1 and I2 I cant change as they are
public interface I1
{
void Display();
}
public interface I2
{
void Display();
void Display2();
}
//I can make changes here
public class MyClass : I1, I2
{
void I1.Display()
{
}
void I2.Display()
{
}
void I2.Display2()
{
}
}
//Calling this method from a diffrent class
void processData(I1 data) //I have to accept I1 interface refrence only
{
var temp = data.Display2(); //Error
}In processData() method data.Display2() is giving error. How I can achive as data is basically MyClass object then how can I call Display2() with I2 reference. Is there any solution like Casting or any SOLID principle which I am missing?

Mohamed Azarudeen ZRank #297 · 8.5K reputationPosted Jun 21, 2023, 12:34 PM EDT
Hi Rushee
// Interface definitions (I1 and I2 remain unchanged) public interface I1 { void Display(); } public interface I2 { void Display(); void Display2(); } // MyClass implementing both I1 and I2 public class MyClass : I1, I2 { void I1.Display() { } void I2.Display() { } void I2.Display2() { } } // Calling the processData method from a different class void processData(I1 data) { if (data is I2 i2Data) { i2Data.Display2(); // Accessing Display2 using I2 reference } else { // Handle the case where the data does not implement I2 } }Deepak RawatRank #646 · 3.7K reputationPosted Jun 22, 2023, 3:37 AM EDT
In order to call the
Display2()method on thedataobject inside theprocessData()method, you need to cast thedataobject to theI2interface. Sincedatais declared asI1, you can't directly access theDisplay2()method using that reference. Here's how you can achieve it:void processData(I1 data) { if (data is I2 dataWithDisplay2) // Check if data implements I2 { dataWithDisplay2.Display2(); // Call Display2() using the I2 reference } }In the above code, we use the
iskeyword to check ifdataimplementsI2. If it does, we assign thedataobject to a new variabledataWithDisplay2, which has the typeI2. Then we can call theDisplay2()method usingdataWithDisplay2.By using this approach, you can handle the scenario where
datacan be an object that implements bothI1andI2, and selectively call methods based on the interface it implements.Rajkiran SwainRank #165 · 14.4K reputationPosted Jun 22, 2023, 12:26 AM EDT
public interface IFirstInterface { void Display(); } public interface ISecondInterface { void Display(); void Display2(); } public class MyClass : IFirstInterface, ISecondInterface { void IFirstInterface.Display() { } void ISecondInterface.Display() { } void ISecondInterface.Display2() { } } void processData(IFirstInterface data) // Accepting IFirstInterface interface reference { data.Display(); // Accessible through IFirstInterface } void processData(ISecondInterface data) // Accepting ISecondInterface interface reference { data.Display2(); // Accessible through ISecondInterface } // Example usage: var myObject = new MyClass(); processData(myObject); // Passes an instance of MyClass to the appropriate processData method