Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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#?

like image 852
startupsmith Avatar asked May 13 '26 01:05

startupsmith


1 Answers

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.

like image 82
rtpg Avatar answered May 14 '26 13:05

rtpg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!