Ata
Ata

Reputation: 12544

work with interface like java in C#

We have such codes in Java

public interface SampleInterface{    
    public void Run();    
}

public void Action(SampleInterface param){
    param.Run();
}

public void someFunction(new SampleInterface(){
      void Run(){
           // the run functions works well
      }
})

but, that is not work in C#, please help me on passing interface as param in C#

My problem is here :

public void someFunction(new SampleInterface(){
    void Run(){
        // the run functions works well
    }
})

it seem that you can not define/new interface when passing interface

Upvotes: 3

Views: 896

Answers (2)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249506

C# does not support inline interface implementations like Java. What you want to achieve would be done using lambdas in C#

public void ActionRunner(Action param)
{
    param();
}
public void someFumction()
{
    ActionRunner(() =>
    {
        // Code goes here
    });
}

Of course implementing the interface in a separate class is also an option but I'm guessing you want something a bit more concise.

Edit:

The Action approach works if you have a single method, if you have multiple methods, and you need to often declare them inline, you could define a helper class, that implements the interface but can have the method implementations specified as Action/Func properties. For interfaces with a single method I would definitely still use the first approach. Here is the implementation of this approach for your interface:

public interface ISampleInterface
{
    void Run();
}

public class SampleClass : ISampleInterface
{
    public Action Run { get; set; }
    void ISampleInterface.Run()
    {
        this.Run();
    }
}

public class SomeClass
{    
    public void ActionRunner(ISampleInterface param)
    {
        param.Run();
    }
    public void someFumction()
    {
        ActionRunner(new SampleClass
        {
            Run = () =>
            {
                // Code goes here 
            }
        });
    }
}

Upvotes: 4

Thiago Loureiro
Thiago Loureiro

Reputation: 1143

This Example Here im using Dependency Injection as well.

    public interface ISampleInterface
{
    void Run();
}

public class SampleClass : ISampleInterface
{
    public void Run()
    {
        // your business Logic Here.
    }
}

public class Test
{
    private ISampleInterface _sampleinterface;

    public Test(ISampleInterface sampleinterface)
    {
        _sampleinterface = sampleinterface;
    }

    public void TestMethod()
    {
        _sampleinterface.Run();
    }
}

Upvotes: 1

Related Questions