I have 2 interfaces as,
public interface I1
{
string GetRandomString();
}
public interface I2
{
string GetRandomString();
}
and in a class, I have implanted both,
public class ClassA : I1, I2
{
string I1.GetRandomString()
{
return "GetReport I1";
}
string I2.GetRandomString()
{
return "GetReport I1";
}
}
Now in main method I want to access , these interface method but not able to
static void Main(string[] args)
{
var objClassA = new ClassA();
objClassA.GetRandomString(); // not able to do this, comile time error ...
}
I know that , I am missing some basic OOPS stuff , just wanted to know that. any Help ?
If you will sometimes be wanting to use one interface and sometimes the other, it will likely be necessary to use a cast for at last one of them. If you control the type and can have one of the interface functions be available directly rather than as an explicit implementation, that will avoid the requirement for casting on that one. To avoid having to typecast either function, you should make them available under separate names within the object. Because in C# any method implementing anyInterface.Boz must be called Boz, the best bet approach is probably to have the implementations of IFoo.Boz and IBar.Boz simply call public methods called FooBoz and BarBoz, which could then be called "directly" without ambiguity.
Although casting to interfaces is inexpensive with classes, it can be expensive with structures. This cost may in some cases be avoided by using static methods like the following:
public interface AliceFoo { void foo();};
public interface BobFoo { void foo();};
static void do_alice_foo<T>(ref T it) where T:AliceFoo
{
it.foo();
}
static void do_bob_foo<T>(ref T it) where T : BobFoo
{
it.foo();
}
This approach allows either 'foo' method to be used without having to typecast anything.
The problem is that these functions are not member functions of MyClass, because they are defined and I1.GetRandomString as I2.GetRandomString. You can only call them on one of the interfaces:
I1 objClassA = new ClassA();
objClassA.GetRandomString();
or
I2 objClassA = new ClassA();
objClassA.GetRandomString();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With