0

I have several objects that implement an interface, and several repositories that perform CRUD operations these objects.

I'm given a GUID and I don't know which class the object is, but it's in one of them, and am using the repository to get the object by its GUID.

The repos return different types.

class Obj1 : IInterface
{
}
class Obj2 : IInterface
{
}
class Obj3 : IInterface
{
}


var repo1 = new Repo1();
var repo2 = new Repo2();
var repo3 = new Repo3();

Obj1 obj = repo1.Get(someGuid);
if (obj != null) 
{ 
    // use obj
}
else 
{
     Obj2 obj2 = repo2.Get(someGuid);
     if (obj2 != null) 
     { 
         // use obj2
     }
     else 
     {
         Obj3 obj3 = repo3.Get(someGuid); 
         if (obj3 != null) 
         { 
             // use obj3
         }
         else 
         {
             // Check another repository
         }
     }
}

This gets more tedious as more objects implement that interface.

Is there a pattern for this or a nicer way of doing it?

2
  • I have to wonder if a better 'if block' really helps you. Maybe there is a way you can know which repo to check
    – Ewan
    Feb 21, 2018 at 11:01
  • Pretending objects can be stored in a database never ends well regardless of what API you put in front of the database.
    – Ian
    Oct 23, 2019 at 15:19

1 Answer 1

1

V2 answer, based on extra info supplied.

Since Repo1, Repo2 etc all have a Get that returns an IInterface, then you can use Func delegates and linq to simplify this:

var repo1 = new Repo1();
var repo2 = new Repo2();
var repo3 = new Repo3();

var repoGetters = new List<Func<GUID, IInterface>>
{
    repo1.Get,
    repo2.Get,
    repo3.Get
};

var obj = repoGetters.First(func => func(someGuid) != null);

obj will then be of type IInterface.

The above assumes a match is guaranteed. If not, replace First with FirstOrDefault and test obj for null to see if a match occurred.

4
  • That would've been a good answer but they don't implement a common interface :(
    – GMon
    Feb 21, 2018 at 11:03
  • @Graham, Do the Gets return a common type?
    – David Arno
    Feb 21, 2018 at 11:04
  • No the objects returned are different types but the objects implement the same interface
    – GMon
    Feb 21, 2018 at 11:05
  • @Graham, answer updated therefore to provide a solution.
    – David Arno
    Feb 21, 2018 at 11:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.