Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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() );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading