Reputation: 41
In C#, is there a way to use an "either or" in the input argument of a method? For example, I have the method ScaleXmin and ScaleXmin_scatter which both return the Points property of the input.
public double ScaleXmin(LineSeries lineSeries)
{
return lineSeries.Points[0].X;
}
public double ScaleXmin_scatter(ScatterSeries scatterSeries)
{
return scatterSeries.Points[0].X;
}
Is it possible to combine this into one method that accepts either LineSeries or ScatterSeries? The reason for doing this is because I've duplicated many methods to accommodate LineSeries and ScatterSeries.
After googling this, I stumbled upon generics, and maybe that's the way to do this. But I'm stuck because they both don't inherit the same class, and makes me think it's incompatible with Generics:
namespace OxyPlot.Series
{
public class ScatterSeries : ScatterSeries<ScatterPoint>
...
public class LineSeries : DataPointSeries
EDIT: Here is an example of what I'd like to run without errors, if possible. Right now I'm getting this error: cannot convert from 'OxyPlot.Series.ScatterSeries' to 'OxyPlot.Series.DataPointSeries' at ScaleXMin(scatter);
using OxyPlot.Series;
LineSeries line = new LineSeries();
ScatterSeries scatter = new ScatterSeries();
public double ScaleXMin(DataPointSeries series)
{
return series.Points[0].X;
}
public void Test()
{
double x = ScaleXMin(line);
double y = ScaleXMin(scatter);
}
Upvotes: 1
Views: 652
Reputation: 7910
Looking at the source code of Oxyplot I found the two classes your talking about, and their base class DataPointSeries. In DataPointSeries
I see the property public IList<IDataPoint> Points
which you are referencing. This makes this a whole lot easier, in that you only need to change the parameter type (and return value) to this:
public double ScaleXMin(DataPointSeries series)
{
return series.Points[0].X;
}
This uses polymorphism, basically, LineSeries inherits from DataPointSeries, and as such an instance of LineSeries is also an instance of DataPointSeries. Meaning we can implicitly cast to a DataPointSeries, this allows us to delegate things to subclasses without having to know those (this is something quite fundamental to Object Oriented Programming). This also allows us to call this method like so:
LineSeries line = new LineSeries();
// Do things with the LineSeries
var x = ScaleXMin(line);
Upvotes: 8