Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Anonymous Interface Implementation [duplicate]

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.

like image 440
Sn0bli Avatar asked Aug 07 '18 08:08

Sn0bli


2 Answers

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();
    };
}
like image 54
Dave Doknjas Avatar answered Nov 10 '22 08:11

Dave Doknjas


Probably you've searched this before and by now the answer is: No. Noway in C#
But I think your main question is Why?

Short Answer: It can be designed in the next C# versions as a feature. It's absolutely possible.

Long Answer: If you want more details on why it's not added to the C# yet; there is a helpful conversation below this exact feature request in the Roslyn (an open-source .Net complier) page at GitHub. Check it out: https://github.com/dotnet/roslyn/issues/13

like image 1
Emran BatmanGhelich Avatar answered Nov 10 '22 07:11

Emran BatmanGhelich