Search code examples
javac#interfaceanonymous

c# Anonymous Interface Implementation


i've already seen this question a few times but i still don't get it. In Java, i can do this:

new Thread(new Runnable(){
  @Override
  public void run() {
    System.out.println("Hello");
  }
}).start();

In my opinion, this is a very nice way to implement interfaces which implementations are only used once. Is there a way to do this in C#? I've already heard of delegates, but that only solves the problems partly since i can only implement one method. What is the "right" way to do that in C# if i have multiple methods? Do i have to implement another class for that?

Thanks in Advance! -Chris

EDIT: I don't want to make a new thread specifically. That was a more general question about the right way to do something like an anonymous implementation from Java in C#. It's not about that specific example.


Solution

  • The general way to do this is C# is to create your own private class. As you noted, other approaches in C# (delegate/lambda) only work when the interface has just one method (i.e., a Java functional interface):

    Java:

    void testMethod()
    {
        x = new ISomeInterface(){
            @Override
            public void method1() { foo(); }
            @Override
            public void method2() { bar(); }
            };
    }
    

    C#:

    void testMethod()
    {
        x = new ISomeInterfaceAnonymousInnerClass();
    }
    
    private class ISomeInterfaceAnonymousInnerClass : ISomeInterface
    {
        public void method1()
        {
            foo();
        }
        public void method2()
        {
            bar();
        }
    }
    

    Here is the simplest conversion when a Java functional interface is involved:

    Java:

    @FunctionalInterface
    interface ISomeInterface
    {
        void method();
    }
    
    void testMethod()
    {
        x = new ISomeInterface(){
            @Override
            public void method() { foo(); }
            };
    }
    

    C#:

    delegate void ISomeInterface();
    
    void testMethod()
    {
        x = () =>
        {
            foo();
        };
    }