Say I have a List<Objects>. I want to define the list of objects in one method, and use them in several others.
Here’s the ways I’ve come up with and I’m looking for more or the correct way to do it.
- You can define
List<Objects>in every method that uses it.- Pros: It works. No chance of getting the wrong variable.
- Cons: Code duplication.
- You can use a private
List<Objects>defined in the class and update it using(ref ListObjects)- Pros: I only have to define it once.
- Cons: I feel like it’s messy and bad practice.
- You can pass
List<Objects>as a parameter to the methods that use it.- Pros: Prevents code duplication
- Cons: Have to make my populate functions return functions, and add parameters to my other methods. Possible conflicts with Events?
So that’s what I’ve come up with. I’m really not sure which to use or if there’s a better way to do this. Thoughts?
EDIT: Including some code as requested.
private List<MedicalPlan> medicalPlansList;
This is the list. It is a list that gets information from a database, here:
private void BindMedicalList()
{
medicalPlansList = new MedicalPlanRepository().RetrieveAll().Where(x => x.Year == year).ToList();
}
Then it’s used to find objects in that list, such as
var result =
medicalPlansList.FirstOrDefault(
c => c.CoverageLevels.Any(p => p.Id == id));
This is, in general, how I’d do it. If you always use the same sequence of functions on a list, consider creating a chained function to handle that. You can also directly pass a function call inside one of the other function calls (as long as it returns a list), but that tends to look messy.
If you are working with an object that has a
List<T>field, I’d do like this:You rarely need to use
refin C#, because it automatically handles pointers for you. You are (usually) not passing around a struct, you are passing around an object reference (which basically is a pointer).