views:

131

answers:

4

Hello, I have a function which implement an interface. something like this:

string IMyInterface.MyFunction()
{
   do something;
}

This function is available outside of my class. All working perfect. Now I also need to call this function from another LOCAL non public function. like this:

void Func2()
{
  string s;
  s = MyFunction();
}

The problem is I get this error: "the name MyFunction does not exist in the current context local"

Any help will be appreciated.

TY.

+6  A: 

You've implemented the interface method explicitly. Cast "this" to the interface, and you're there:

void Func2()
{
    string s = ((IMyInterface)this).MyFunction();  
}
Willem van Rumpt
Or implement the function implicitly.
SLaks
Working Perfect. TY.
+3  A: 

It is explicitly implemented. You can only call it from a reference of the type IMyInterface. To call it internally, you need to cast this.

s = ((IMyInterface)this).MyFunction();

Consider to implement it implicitly, explicit implementations are tricky, you need a good reason to use it.

Stefan Steinegger
I saw your comment after I deleted my redundant answer. (For the record, I agree.)
Anthony Pegram
Explicit implementation is one of the beauties of C#, if you ask me. I really miss that sometimes. Casting to interface can be a really clear way to write self-explaining code. Off course depending on what your interfaces are and so on.
Krumelur
Working Perfect. TY.
@Krumelur: there are some tricky situations with inheritance and reflection. I had issues with NHibernate. It could be a nice feature, but you have to know what you are doing.
Stefan Steinegger
@Stefan Steinegger: True. But then, I believe that applies for most things :)
Krumelur
+2  A: 

As mentioned by the other posters, you have implemented the interface explicitly. The other option is to implement it like so:

string MyFunction()
{
   do something;
}

In my experience you only explicitly implement an interface when you are worried that the names of functions in multiple interfaces will collide, but they have different implementations.

Chris
A: 

I often use a variation of the following pattern with explicit interfaces:

string IMyInterface.MyFunction()
{
    _myPrivateFunction();
}

string _myPrivateFunction()
{
    //Do Stuff...
}
Rodrick Chapman