Reputation: 47
I'm new to C# generics and don't know a lot about it and still learning. I want to write a single generic method for these two methods. But since the method one receives List<List<> as parameter and method 2 receives string, so not sure how can i write a single generic method for these two: Method 1
public static void WriteReports(string expectedDailyData, string actualDailyData, string fileName)
{
var baseline = FormatData(expectedDailyData);
var actual = FormatData(actualDailyData);
var baselineCSV = fileName + "Baseline";
var actualCSV = fileName + "actual";
var regressCSV = fileName + "RegressReport";
WriteReport(baseline, baselineCSV); //this is generic method which handles List and List<List(object)>
WriteReport(actual, actualCSV);
try
{
WriteRegressionReport(baseline, actual, regressCSV);
}
catch (ArgumentOutOfRangeException)
{
//catch
}
}
Method 2
public static void WriteReports(List<List<object>> baseline, List<List<object>> actual, string fileName)
{
var baselineCSV = fileName + "Baseline";
var actualCSV = fileName + "Actual";
var regressCSV = fileName + "RegressReport";
WriteReport(baseline, baselineCSV);
WriteReport(actual, actualCSV);
try
{
WriteRegressionReport(baseline, actual, regressCSV);
}
catch (ArgumentOutOfRangeException)
{
// handle exception
}
}
Any help would be greatly appreciated.
Upvotes: 0
Views: 62
Reputation: 271420
You should not use generic methods here. Generics should be used when your method can work with any type (satisfying some constraints). If your method can only work with two types: string
and List<List<object>>
, then you should leave it as two overloads.
You can reduce the code duplication though. Observe that the body of the second method is "inside" the first method. You can replace everything after the second line of the first method with a call to the second method:
public static void WriteReports(string expectedDailyData, string actualDailyData, string fileName)
{
var baseline = FormatData(expectedDailyData);
var actual = FormatData(actualDailyData);
WriteReports(baseline, actual, filename);
}
Upvotes: 2