C#: Split string and assign result to multiple string variables
You can use Tuples (added in .Net 4). Tuples in MSDN
This:
public class MySplitter
{
public MySplitter(string split)
{
var results = split.Split(',');
NamedPartA = results[0];
NamedpartB = results[1];
}
public string NamedPartA { get; private set; }
public string NamedPartB { get; private set; }
}
Could be achieved with something like this:
public Tuple<string,string> SplitIntoVars(string toSplit)
{
string[] split = toSplit.Split(',');
return Tuple.Create(split[0],split[1]);
}
With a Tuple you can use:
var x = SplitIntoVars(arr);
// you can access the items like this: x.Item1 or x.Item2 (and x.Item3 etc.)
You can also create a Tuple for using Tuple<string,int>
etc.
Also... I don't really like out parameters, so you emulate returning multiple values using a Tuple (and obviously, also of varying types). this:
public void SplitIntoVariables(string input, out a, out b, out c)
{
string pieces[] = input.Split(',');
a = pieces[0];
b = pieces[1];
c = pieces[2];
}
turns into this:
public Tuple<string,string,string> SplitIntoVariables(string[] input)
{
string pieces[] = input.Split(',');
return Tuple.Create(pieces[0],pieces[1],pieces[2]);
}
Other (more imaginative) options could be creating an ExpandoObject (dynamic) that holds your values (something akin to ViewBag in ASP.NET MVC)
I agree. Hiding the split in an Adapter class seems like a good approach and communicates your intent rather well:
public class MySplitter
{
public MySplitter(string split)
{
var results = string.Split(',');
NamedPartA = results[0];
NamedpartB = results[1];
}
public string NamedPartA { get; private set; }
public string NamedPartB { get; private set; }
}