1

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?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
burak
  • 11
  • 4

2 Answers2

1

No, in C# you can not send array of variable references.

But what you can do is create a class with some properties, and then use reflection to fill them.

See Enumerating through an object's properties (string) in C# and Set object property using reflection and How to dynamically cast an object of type string to an object of type T on some details.

Community
  • 1
  • 1
Pavel Krymets
  • 6,253
  • 1
  • 22
  • 35
1

I suggest you return a List

List<object> variables = ReadVariablesFromString(str, separators);

Where each entry in the list will be the values your parse from the input string, for example

variables.ElementAt(0) will be 'a'

Since the type of the list is 'object', you can store any data type in there, since each type ultimately inherits from object anyway. You would need to cast the data when you need to use it though

char letter = (char)variables.ElementAt(0)

But you must be doing something similar already, otherwise how would you know which variable to put in each incoming out parameter.

Doing this means you have more flexibility in the amount of variables you can return from ReadVariablesFromString()

Jason Evans
  • 28,906
  • 14
  • 90
  • 154