//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?
Deepak RawatPosted Jun 22, 2023, 7:37 AM
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: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 SwainPosted Jun 22, 2023, 4:26 AM
Mohamed Azarudeen ZPosted Jun 21, 2023, 4:34 PM
Hi Rushee