[Solved] Can we call interface methods from windows forms in c#? [closed]


Yes, it’s a common practise in any OOP based language to use only the definition of an object so that implementation details can be changed at a later time

Let’s say you have the following interface

public interface ISearchProvider {
     ISearchResult Search(ISearchRequest request);
}

If you now implement a property inside your windows forms, that gets set through a constructor parameter, you can create a form that can implement several versions of the ISearchProvider for specific repositories (eg: Sql, FileSystem, Csv, …)

The property you can then implement like this

private readonly ISearchProvider _searchProvider;
public SearchForm(ISearchProvider searchProvider) {
    _searchProvider = searchProvider;
}

The calling class would then have to initialize the SearchForm with a specific implementation of the ISearchProvider. So, lets say we have a mock ISearchProvider, implemented in the following way

public class MockedSearchProvider : ISearchProvider {
    public ISearchResult Search(ISearchRequest request) {
        ISearchResult result = null;
        // implement searching here
        return result;
    }
}

We could then call the SearchForm in the following way

var form = new SearchForm(new MockedSearchProvider());
form.Show();

in the form, depending on button click, you can then implement the search like:

protected void SearchButton_Click(object sender, EventArgs e) {
    if (_searchProvider == null) {
        // search provider wasn't set
        return;
    }
    var result = _searchProvider.Search(GetSearchRequest());
    // handle the result
}

private ISearchRequest GetSearchRequest() {
    // return a search request, for this question is currently null
    return null;
}

solved Can we call interface methods from windows forms in c#? [closed]