startupsmith
startupsmith

Reputation: 5764

Converting Java to C#: Declaring interface and creating an instance?

I am converting some java code C# for use in my MonoDroid application. I have some snippets where interfaces are declared and then initialized in to objects. I am not 100% sure on the best approach to implement these in to C#.

For example:

public class NumberPicker {

    public interface Formatter {
        String toString(int value);
    }

    public static final NumberPicker.Formatter TWO_DIGIT_FORMATTER =
            new NumberPicker.Formatter() {
             //some code here
            };

}

What would be the equivalent or best approach to do this in c#?

Upvotes: 3

Views: 592

Answers (3)

emalamisura
emalamisura

Reputation: 2904

So the easiest way I have found to handle this situation is to create a private nested class within your main class and then have it inherit from as many interfaces as you need. Such as IOnClickListener, IOnMouseDownListener, and then declare it at the top of your class and reuse it over and over wherever needed. Makes it much easier... If you have interfaces that repeat or have the same method names you can declare them explicitly, for example

IOnClickListener.OnClick(object sender, EventArgs) {

}

Just as an example, you would obviously want to use the real method names and interface names. Also don't forget to dispose of the instance in your OnDestroy.

Upvotes: 0

rtpg
rtpg

Reputation: 2439

for simple "single-use" interfaces with one function (like event listeners, for example), you could think of rewriting the code to use delegates and anonymous functions instead.

delegate String Formatter(int n);
...

Formatter TWO_DIGIT_FORMATTER = delegate(int n) {
                                         //code here
                                       };

you can then use TWO_DIGIT_FORMATTER like a function ( TWO_DIGIT_FORMATTER(12) ).

Anonymous classes (which is what's happening in your java code) don't exist in C#, but delegates suffice in cases like this.

Upvotes: 6

Matt Murphy
Matt Murphy

Reputation: 421

You would have to create a class that implements the Formatter interface and then create an instance of that.

i.e.

public class MyFormatter : IFormatter
{
     public string ToString(int value)
     {
       //implementation
     }
}

Then create an instance of MyFormatter with the new operator.

public static IFormatter TWO_DIGIT_FORMATTER  = new MyFormatter ();

The 'I' prefix for interfaces is something done in the .net world but it isn't required, just convention.

Upvotes: 0

Related Questions