Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Generic method for list of different objects

I have a situation in C# web api function where I will need to retrieve a list of different objects from my database and need to implement some logic by invoking various methods.

How can I better achieve this by writing a Generic function for all 3 objects

example

there are two scenarios of locking list

  1. whole list is locked (do not proceed and throw exception if whole list is locked)

  2. only a single entity is locked (filter and remove this element if locked from the list)

    List<Object1> list1;
    List<Object2> list2;
    List<Object3> list3;
    
    private FilterLockedEntities(List<Object1> list1){
    
       if(list1[0].isListLocked) //whole list is locked
         throw ValidationException("Message")
    
       list1.RemoveAll(a => a.IsLocked); //filter locked entities
    
       //some more logic common to all
    
    }
    
    private FilterLockedEntities(List<Object2> list2){
    
       if(list2[0].isListLocked) //whole list is locked
         throw ValidationException("Message")
    
       list2.RemoveAll(a => a.IsLocked); //filter locked entities
    
       //some more logic common to all
    
    }
    
    private FilterLockedEntities(List<Object3> list3){
    
       if(list3[0].isListLocked) //whole list is locked
         throw ValidationException("Message")
    
       list3.RemoveAll(a => a.IsLocked); //filter locked entities
    
       //some more logic common to all
    
    }
    

I have the same logic in each of the three function but with List of different entities.

Is there a way where I can use a single method instead of three different functions its hard to maintain due to redundant logic. If there is a change in logic it needs to be updated in all the three places.

like image 579
Shashi Avatar asked Sep 26 '22 10:09

Shashi


1 Answers

Create a new interface:

public interface ILockable
{
    bool isListLocked();
}

Then make your object inherit the interface in their class declarations:

class Object1 : ILockable
{
    public IsLocked()
    {
        // Your code here...
    }
}
...
class Object2 : ILockable ...
class Object3 : ILockable ...

Then make your function accept a List of ILockable objects:

private FilterLockedEntities(List<ILockable> list)
{
    // Your code here...
}
like image 105
Lemonseed Avatar answered Sep 28 '22 03:09

Lemonseed