I have a structed called ValueFrequency which starts its life as a struct where you (for statistical reasons) could store a (double) value, and an (int) frequency (telling how many times this value occured in a set of data. E.g. if you had a list/array with the values: 1,1,1,2,2,3,4,4,4,4,4 it could be stored as a list/array of ValueFrequency in stead: (1,3),(2,2),(3,1),(4,5).
Anyway I found in stead of hardcoding my scruct to use double I could use a generic, so I could use it with outher data-types (e.g. a Point, when using it to store data from a 2-dimentional set of data).
Simplified version of the struct:
public struct ValueFrequency<T> : IComparable, ICloneable where T : IComparable
{
public T value;
public int Frequency;
}
My problem is I want to use this struct with both structs/classes supporting ICloneable and ValueTypes like double. How would I write a copy-constructor (copying its fields from another ValueFrequncy), where it will either simply assign the same value (if type is ValueType) or Clone if the struct/class supports IClonable:
public ValueFrequency(ValueFrequency<T> valueFrequency)
{
if (typeof(T).IsValueType)
this.Value = valueFrequency.Value;
else if (T is supporting IClonable) // pseudo-code ???
this.Value = (T)valueFrequency.Value.Clone();
else
throw new Exception("T must be ValueType or IClonable") ;
this.Frequency = valueFrequency.Frequency;
}
As you can see my problem is testing for if T is IClonable, and the actual cloning (typecasts T to IClonable to perform the cloneing).