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?

  • 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 '18 at 11:01
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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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