KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
In C# I sometimes wish I could make special methods for certain "instantiations" of generic classes. UPDATE: The following code is just a dumb example of a more abstract problem - don't focus too much on time series, just the principles of "adding extra methods" for certain T . Example: class Timeseries<T> { ... TimeSeries<T> Slice(...) { ... } } In the case where T is double, I would like some extra methods, like Integrate() , Interpolate() and so on that make only sense for double , because I need to do arithmetic on them. There are several ways to do this, but I cannot find one that I'm satisfied with. 1. Inherit into a special class class TimeseriesDouble : Timeseries<double> { double Interpolate(...) { ... } ... } cons: TimeseriesDouble.Slice() will return a new Timeseries<double> object, now missing my special methods. 2. External methods public static double Interpolate(Timeseries<double> ts, ...) { ... } cons: Breaks with OO principles. And I don't want to put my methods away. Also, the methods might need private/protected state. 3. Extension methods Same as 2, just with a nicer calling syntax. 4. Common base class class TimeSeries_base { ... } class TimeSeries<T> : TimeSeries_base { .. typesafe versions of methods .. } class TimeSeriesDouble : TimeSeries_base { .. typesafe versions of methods .. } cons: too much duplication of things from TimeSeries_base into the two subclasses. The base class might become just a place holder for utility functions for the sub classes. pro:
Tags (comma-separated)
Save Edits
Cancel