Camilla
Camilla

Reputation: 969

Accessing a method of an interface

I'm starting to work with interfaces and I really don't understand... The situation is this: there is a webcontrol (called TableControl) which displays a table of items using a repeater. TableControl includes also a line of cursors (first, previous, next, last) that implements paging. The cursors are imported from another webControl (CursorControl). TableControl implements also an interface, in which I declare some method to do paging.

*) CursorControl

 public class CursorControl 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    private string cursor_value;

    public string CursorValue
    {
        get { return cursor_value; }
        set { cursor_value = value; }
    }

    // Called when cursor is clicked.
    protected void lnkClick_Command(object sender, CommandEventArgs e)
    {
        cursor_value = e.CommandArgument.ToString();
    }

}

*) TableControl

public partial class TableControl : System.Web.UI.UserControl, IPageableControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(isPostBack)
         {
               currentPage = CursorControl.CursorValue;
               OtherPage(currentPage);
          }
    }

    public int currentPage;

    void IPageableControl.OtherPage(int i)
    {
        if (i == 0)
            currentPage = 2;
        else if (i == 1 || i == (-1))
            currentPage += i;
        else
            currentPage = 25;

    }


 }

*) Interface

   public interface IPageableControl
{
    // Summary:
    //     Go to page
    void OtherPage(int i);
}

When a user clicks on a cursor I pass the value to TableControl, which should start the method OtherPage. But it doesn't work, it says that OtherPage is not in the current context.

How can I access a method of an interface??

Upvotes: 1

Views: 124

Answers (1)

MasterMastic
MasterMastic

Reputation: 21306

You need to make this line:

void IPageableControl.OtherPage(int i)

into this:

void OtherPage(int i)

The first one is explicit, the second is implicit. (What are the differences?)

  • When you explicitly mention the interface type, you need to convert your type to it in-order to access those methods. (Why implement interface explicitly?)
  • When you implicitly implement you just treat it as a regular method (the implementation is exactly the same, and the compiler will ensure that it's there so you don't have to worry about it. In the code you won't see any difference. If you do want to see (which helps) you could get a plugin. ReSharper does this very well).

By the way, on Visual Studio, when you want to implement an interface, press Ctrl + . (dot) on the interface(s) name and it will ask you how to implement it. It makes it much less tedious because you won't have to type the signatures (method names) by yourself.

Visual Studio Implementing Interfaces

Upvotes: 1

Related Questions