This is probably an old problem in a new bottle. But, I never encountered this myself before.
I am developing a statistics library in .net. I have developed a Set<T>
data structure. Now, I want to derive a data structure named DescriptiveStatisticalSet<T>
, and I want this set to be able to operate only on integer and double types.
Say, I have the following interfaces and classes:
public interface IIntegerDataType
{
int Data { get; set; }
int Add(int other);
}
public interface IDoubleDataType
{
double Data { get; set; }
double Add(double other);
}
public class IntegerDataType : IIntegerDataType
{
public int Data { get; set; }
public int Add(int other)
{
return Data + other;
}
}
public class DoubleDataType : IDoubleDataType
{
public double Data { get; set; }
public double Add(double other)
{
return Data + other;
}
}
Is it possible to create a generic type DataType<T>
so that both (and only) IntegerDataType
and DoubleDataType
could be accessed through that generic type?
EDIT
I have devised the following solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataTypeNamespace
{
public interface IDataType
{
object Add(object other);
void SetVal(object other);
}
public interface IDataType<T> where T : IDataType, new()
{
T Add(T other);
}
class IntegerDataType : IDataType
{
public int Data { get; set; }
public object Add(object other)
{
int o = ((IntegerDataType)other).Data;
return Data + o;
}
public void SetVal(object other)
{
Data = (int)other;
}
}
class DoubleDataType : IDataType
{
public double Data { get; set; }
public object Add(object other)
{
double o = ((DoubleDataType)other).Data;
return Data + o;
}
public void SetVal(object other)
{
Data = (double)other;
}
}
public class DataType<T> : IDataType<T> where T : IDataType, new()//https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/new-constraint
{
IDataType _item;
public DataType(IDataType item)
{
_item = item;
}
public T Add(T other)
{
object o = _item.Add(other);
T t = new T();
t.SetVal(o);
return t;
}
}
public class MainClass
{
public static void Main(string[] args)
{
//IntegerDataType item1 = new IntegerDataType();
//item1.Data = 10;
//IntegerDataType item2 = new IntegerDataType();
//item2.Data = 20;
//DataType<IntegerDataType> l1 = new DataType<IntegerDataType>(item1);
//IntegerDataType sum1 = l1.Add(item2);
DoubleDataType item3 = new DoubleDataType();
item3.Data = 10.5;
DoubleDataType item4 = new DoubleDataType();
item4.Data = 20.5;
DataType<DoubleDataType> l2 = new DataType<DoubleDataType>(item3);
DoubleDataType sum2 = l2.Add(item4);
}
}
}
Can someone review this?
Or, maybe help me to improve?