Using generics to make an algorithm work on lists of "something" instead of only String's
- by Binary255
Hi,
I have a small algorithm which replaces the position of characters in a String:
class Program
{
static void Main(string[] args)
{
String pairSwitchedStr = pairSwitch("some short sentence");
Console.WriteLine(pairSwitchedStr);
Console.ReadKey();
}
private static String pairSwitch(String str)
{
StringBuilder pairSwitchedStringBuilder = new StringBuilder();
for (int position = 0; position + 1 < str.Length; position += 2)
{
pairSwitchedStringBuilder.Append((char)str[position + 1]);
pairSwitchedStringBuilder.Append((char)str[position]);
}
return pairSwitchedStringBuilder.ToString();
}
}
I would like to make it as generic as possible, possibly using Generics. What I'd like to have is something which works with:
Anything that is built up using a list of instances.
Including strings, arrays, linked lists
I suspect that the solution must use generics as the algorithm is working on a list of instances of T (there T is ... something). Version of C# isn't of interest, I guess the solution will be nicer if features from C# version 2.0 is used.