Home > other >  Pass generic type of variable to function (.Net Framework 4.8)
Pass generic type of variable to function (.Net Framework 4.8)

Time:12-30

I have about 7 function that to the same, being the only difference the class they work in.

Ex:

private void modifier()
        {
            foreach (variable_type entry in new Parser().ParseFiles(generic_input))
            {...}
            return;
        }

and

private void modifiertypes()
            {
                foreach (variable_type entry in new Parser2().ParseFiles(generic_input))
                {...}
                return;
            }

Where the difference is the used class (Both classes contain the same method but with different code).

Is it possible to make the Parser class a variable to input in a function?

CodePudding user response:

That sounds rather obvious, that's what interfaces are for.

Make all parsers implement the same interface

public interface IParser
{
    IEnumerable<....> ParseFiles( .... );
}

public class Parser: IParser { ...

public class Parser2: IParser { ...

and pass instance of the interface into the method

private void modifier( IParser parser )
{
    foreach (variable_type entry in parser.ParseFiles(generic_input))
    {...}
    return;
}

var result1 = modifier( new Parser() );
var result2 = modifier( new Parser2() );
  •  Tags:  
  • c#
  • Related