I have the following situation which I think is a perfect use of delegates, however, I I'm new to using delegates and am having some problems getting it to work.
I call the AddVariable method from this code, which decides the appropriate value for T.
switch (datum.DataType) {
case SupportedDataTypes.Int:
table = AddVariable<int>(table, datum);
break;
case SupportedDataTypes.Float:
table = AddVariable<float>(table, datum);
break;
case SupportedDataTypes.String:
table = AddVariable<string>(table, datum);
break;
case SupportedDataTypes.ChooseType:
throw new ArgumentException("type not chosen");
default:
throw new ArgumentOutOfRangeException();
}
But AddVariable just selects the appropriate method based on another switch. These methods need to be generic since they act on several different types.
static DataTable AddVariable<T>(DataTable table, Datum datum) {
DataTable newTable = table.Clone();
AddVariableColumn(datum, newTable);
switch (datum.MixingTypeOfVariable) {
case VariableMixingType.Balanced:
table = AddBalancedValues<T>(table, datum);
break;
case VariableMixingType.Looped:
table = AddLoopedValues<T>(table, datum);
break;
case VariableMixingType.EvenProbability:
table = AddEvenProbabilityValues<T>(table, datum);
break;
case VariableMixingType.CustomProbability:
throw new NotImplementedException();
default:
throw new ArgumentOutOfRangeException();
}
Debug.Log($"table now has {table.Rows.Count} rows");
return newTable;
}
I thought of making AddLooped, AddBalanced, and AddEvenProbability values to be delegates, but I can't seem to make any delegates with < T >. Then I could choose the delegate and call that method without a need for AddVariable at all. They all have the same signature (except for T) and basically do the same thing, but modified slightly.
Edit: pseudo code expected:
AddVariable< int >(table, datum, function to apply values);
Note that the function to apply values needs to know it’s < int > too. Since it’s generic as well.
I found some discussions online about using generic delegates but they seemed to all have something to do with a Stack. Which doesn't sound like what I want.
I saw some things online about using Func<> but it wasn't clear that that is the right path, and I didn't fully understand it.
It's also possible that my approach is backwards, so if there are any ideas on how to improve design, that would be great as well.