I need to read a tab (or comma) separated text and assign them to a list of built-in variables (int, char, string, etc. but not object). I want to handle this with a generic method. Here is the working code I am using for the case with three variables.
public static void ReadVariablesFromString<T0, T1, T2>(out T0 input0, out T1 input1, out T2 input2, string stringIn, char[] separators)
{
string[] stringParts = stringIn.Split(separators);
input0 = ConvertTo<T0>(stringParts[0]);
input1 = ConvertTo<T1>(stringParts[1]);
input2 = ConvertTo<T2>(stringParts[2]);
}
public static T ConvertTo<T>(object value)
{
return (T)Convert.ChangeType(value, typeof(T));
}
When I want to assign the tab separated text to three variables of different type, this is what I use:
string str = "a\t123\tbcd";
char var1;
int var2;
string var3;
char[] separators = { '\t' };
ReadVariablesFromString(out var1, out var2, out var3, str, separators);
Is there a way to generalize this model for different number of variables? Is it possible to write a generic method that accepts different number of variables for this specific case?
One of the other solution might be writing this method for a variable list with different types. Instead of passing variables one by one, is there a way to pass them in a list?