0

Simplifying the question, I have these 2 functions

private void ReadFilesCommon(List<string> input)
{
    foreach (string entry in input)
    {
        new Class1(entry, entry.length);
    }
}

and

private void ReadFilesCommon2(List<string> input)
{
    foreach (string entry in input)
    {
        new Class2(entry);
    }
}

Is it possible to generalize these functions?

My main problem is the different inputs, but putting that aside, is it possible with interfaces?

Something like

private void ReadFilesCommon2(IClass Class)
{
    foreach ()
    {
        new Class(input1);
    }
}
5
  • 3
    You question is a little too generic/vauge. What does your foreach loop do with the class objects it instatiates? How much of the code is repated vs unique/depedant on the class it is working with (i.e. Class1 vs Class2)? Commented Dec 29, 2022 at 20:22
  • 1
    Class1 is completely different from Class2 and the foreach doesnt interact with the Class only with the input Commented Dec 29, 2022 at 20:36
  • 1
    you can try to define an interface that both Class1 and Class2 implement, and then pass an instance of that interface to the generalized function. Commented Dec 29, 2022 at 20:41
  • you're telling me that i should make the constructer as a function and use it with the interface. Commented Dec 29, 2022 at 20:51
  • 2
    How are the inputs provided, where do they come from? Your question is still too vague. Commented Dec 29, 2022 at 20:55

1 Answer 1

1

Factory method/interface seem to be what you are looking for:

private void ReadFiles<T>(List<string> input, Func<string, T> creator)
{
    foreach (string entry in input)
    {
        var item = creator(entry);
    }
}

// and replace your functions with:
ReadFiles(input, s => new Class1(s)); // ReadFilesCommon
ReadFiles(input, s => new Class2(s, s.Length)); // ReadFilesCommon1

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.