Multiple Interfaces

G

Gav

I have a class that implements 2 interfaces and have got myself a bit stuck.
What I am trying to do is hide the implementation of the class so that you
are forced to use one of the interfaces. Problem I have now is that my
constructor needs to call a method that is from one of the interfaces and
I'm not sure how to call it. Can anybody point me in the right direction?
Simple example below

thanks

Gav.

public interface1
{
void Method1();
}

public interface2
{
void Method2();
}

public class myClass: interface1, interface2
{
public myClass()
{
// How to call Method1?
}

void interface1.Method1()
{

}

void interface2.Method2()
{

}
}
 
J

Jon Skeet [C# MVP]

I have a class that implements 2 interfaces and have got myself a bit stuck.
What I am trying to do is hide the implementation of the class so that you
are forced to use one of the interfaces. Problem I have now is that my
constructor needs to call a method that is from one of the interfaces and
I'm not sure how to call it. Can anybody point me in the right direction?
Simple example below

Cast "this" to the interface, e.g.

((interface1)this).Method1();

Jon
 
M

Marc Gravell

Well, using explicit implementation you have to use the interface yourself:

((interface1)this).Method1();

Alternatively, use a private backing method:

private void Method1() {
// actual code here
}
void interface1.Method1() {
Method1(); // use the private method
}

Now your ctor can just call Method1() directly, but it isn't public.

Marc
 
W

wilbain

I have a class that implements 2 interfaces and have got myself a bit stuck.
What I am trying to do is hide the implementation of the class so that you
are forced to use one of the interfaces. Problem I have now is that my
constructor needs to call a method that is from one of the interfaces and
I'm not sure how to call it. Can anybody point me in the right direction?
Simple example below

thanks

Gav.

public interface1
{
void Method1();

}

public interface2
{
void Method2();

}

public class myClass: interface1, interface2
{
public myClass()
{
// How to call Method1?
}

void interface1.Method1()
{

}

void interface2.Method2()
{

}

}

If I were you I would do the following:

public interface IInterface1
{
void Method1();
}

public interface IInterface2
{
void Method2();
}

public class MyClass : IInterface1, IInterface2
{
public MyClass()
{
Method1Internal();
Method2Internal();
}

void IInterface1.Method1()
{
Method1Internal();
}

void IInterface2.Method2()
{
Method2Internal();
}

private void Method1Internal()
{

}
private void Method2Internal()
{

}
}

Having to cast a class within itself to one of it's interface
realizations just to call one of its methods smacks of poor design.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top