I have a small peice of code where for each is being used. I have optimized my code, but my boss expects me to optimize it even further more. I have no idea what further optimization can be done here.
foreach (Match match in matches) {
//When oveeride is false and you have to download all the files
if (Override.Equals(false)) {
//putting the matches from regular expression into DownloadFileStruct oject
df = new DownloadFileStruct(match.Groups[1].Value, match.Groups[2].Value);
//Adding DownloadFileStruct object to a array list
DownloadFileList.Add(df);
}
//When override is true and a paticular file has to be downloaded
else if (match.Groups[2].Value.Equals(OverrideFileName)) {
//putting the matche from regular expression into a DownloadFileStruct oject
df = new DownloadFileStruct(match.Groups[1].Value, match.Groups[2].Value);
//Adding DownloadFileStruct object to a array list
DownloadFileList.Add(df);
}
}
}
What my boss says "You do not need an ‘if’ and an ‘else if’ that execute the same code in both branches".
Well it's not really optimization, but your code would be simpler as:
if (!Override || match.Groups[2].Value == OverrideFileName)
{
var df = new DownloadFileStruct(match.Groups[1].Value,
match.Groups[2].Value);
DownloadFileList.Add(df);
}
(It's not clear where you're declaring df
, but it would make sense to declare it inside the if
statement, assuming you're not actually using it elsewhere. Or get rid of it entirely and just use DownloadFileList.Add(new DownloadFileStruct(...))
.
See more on this question at Stackoverflow