I want to pass either string
or List<string>
as a parameter, like the way I could do in JavaScript, and then evaluate what type is it and do the appropriate actions. Now I can do it like this:
public static class TestParser
{
static void Parse(string inputFile)
{
// Lots of code goes in here
}
static void Parse(List<string> inputFileList)
{
// Lots of code goes in here too
}
}
What the code inside these methods do, is basically Parsing with some programs either one file or list of files, depends what type is given.
If I will have lots of code, should I duplicate it, or should I create sub method which will contain the code, or is there another cool way I can do this in c#?
Depending on exactly what Parse() is supposed to do, a reasonable pattern might be
static void Parse(string inputFile)
{
// Lots of code goes in here
}
static void Parse(List<string> inputFileList)
{
foreach (var inputFile in inputFileList)
Parse(inputFile);
}
UPDATE
The alternative has been suggested to create a new List<string>() { inputFile}
and call Parse(List<string>)
instead of separating the processing code out into a separate method.
static void Parse(List<string> inputFileList)
{
// Lots of code goes in here too
}
static void Parse(string inputFile)
{
Parse(new List<string>() { inputFile });
}
In almost all cases, this is only a question of style. I prefer my solution because it is clearer at first glance (to me, at least) what is happening, and because I have worked on very high volume systems where the CLR's ability to dispose short-lived objects became a performance issue. 99.99% of even performance critical apps will not run into that particular issue.
Any performance difference will only manifest if you have such a high volume of separate calls that you are pushing the CLR's CG to the breaking point. If you have a modest to even high volume of calls to the method, // Lots of code goes in here
's processing time is likely to make the performance cost of creating the new list nearly immeasurable.
For nearly all cases, the two approaches differ only in style, and are both appropriate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With