How can I call a method which has Interface as one of the parameter in C#?

1.9k views Asked by At

I have the following method (3rd party sdk method being implemented in my dll):

public void PlaceItem(myItemData item, IRequest request)
{
    var item = (ItemClassData)item; //**myItemData is the base class for ItemClassData**
    item.Id = 101;
    request.Succeeded(item.Id);
}

The interface parameter is as below:

public interface IRequest
{
    void Failed(string Error);
    void Succeeded(string ItemId);
}

I want to call this method from a function. I know how to pass an object as the first parameter when I call this method. But how do I pass the second parameter (Interface). Any help is greatly appreciated.

3

There are 3 answers

2
Ondrej Janacek On BEST ANSWER

Just create a class that implements this interface like

public class MyClass : IRequest
{
    public void Failed(string Error) { // do something }
    public void Succeeded(string ItemId) { // do something }
}

create instance of it and pass it to the method

var inst = new MyClass();    
PlaceItem(..., inst);
1
Sachin On

You can pass object of any class which implements that interface.

for example:

public class MyClass : IRequest
{
    // class definition and implementation of methods
   void Failed (string Error) {};
   void Succeeded (string ItemId) {};
}

Now you can pass the object of MyClass in that method.

// create an instance of MyClass
MyClass objMyClass = new MyClass();

// call the method
PlaceItem(myDataItem, objMyClass);
1
Kaf On

You can pass any implementation of IRequest as the second parameter.

public class Request : IRequest
{
    public void Failed(string Error)
    {
       //do something here
    }

    public void Succeeded(string ItemId);
    {
       //do something here
    }
}

//Calling your method
Request mySecondPara = new Request();

PlaceItem(item, mySecondPara)

Also you can use an IOC container (Unity, Ninject) to do the job. This is also known as Dependency Injection.