penguru
penguru

Reputation: 4370

Interface implementation in C#

In Java, while creating a new object you can implement the interface as inline block easily.

Example :

dialog.setOnKeyListener(new Dialog.OnKeyListener() {

        @Override
        public boolean onKey(DialogInterface arg0, int keyCode,
                KeyEvent event) {
            // TODO Auto-generated method stub
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                finish();
                dialog.dismiss();
            }
            return true;
        }
    });

What is the equivalent of this code in C# ?

Upvotes: 1

Views: 228

Answers (2)

Dave Doknjas
Dave Doknjas

Reputation: 6542

While you should prefer the idiomatic solution presented by 'recursive', if you have no choice about whether OnKeyListener remains an interface, then you can explicitly do what Java is implicitly doing (i.e., assume that you have to keep OnKeyListener as an interface):

public void test()
{
    dialog.OnKeyListener = new OnKeyListenerAnonymousInnerClassHelper();
}

private class OnKeyListenerAnonymousInnerClassHelper : Dialog.OnKeyListener
{
    public bool onKey(DialogInterface arg0, int keyCode, KeyEvent @event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            finish();
            dialog.dismiss();
        }
        return true;
    }
}

Upvotes: 0

recursive
recursive

Reputation: 86064

The idiomatic solution to this problem in C# doesn't use interfaces at all, rather events and delegates:

dialog.KeyPress += (object sender, KeyEventArgs e) => {
        if (e.keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            dialog.dismiss();
        }
};

There is no anonymous way of implementing interfaces in C#, but it's rarely necessary, because delegates and lambda expressions are often used in place of single-method interfaces.

Upvotes: 2

Related Questions