RobVious RobVious - 5 months ago 20
C# Question

Pattern for updating references of interface implementations

I have the following interface:

public interface ISearchProperties {
string CurrentUserLocation { get; set; }
string SearchUsername { get; set; }

With the following implementations:

public class BroadcastPreviewDto : ISearchProperties {
// other properties
public class ProfileSearchDto : ISearchProperties {
// other properties

I have the following functions:

public void PrepSearchProperties(ProfileSearchDto query) {
// do a bunch of stuff to query properties here (only on ISearchProperties properties)
public void PrepSearchProperties(BroadCastPreviewDto query) {
// do a bunch of same stuff to query properties here (only on ISearchProperties properties)

The problem is that this isn't very DRY - the function bodies are exactly the same thing. I tried doing this:

public void PrepSearchProperties(ISearchProperties query) {
// do a bunch of stuff to query properties here

But this doesn't quite work unless I declare the original
, which strips the implementing class properties.

What pattern can I follow to DRY my code up?


If you have this function definition:

public void PrepSearchProperties(ISearchProperties query) {
    // statements of the form:
    query.SearchProperty = 123;

Then you can pass any implementation of ISearchProperties to it. Example:

public class BroadcastPreviewDto : ISearchProperties {
    // implement ISearchProperties here
    // more, implementation-specific properties, e.g.
    public string BroadcastType { get; set; }

var bp = new BroadcastPreviewDto() {
    // set implementation specific properties here
    BroadcastType = "example"

// this compiles and executes fine

// Same instance as before. No properties stripped.