I created a method to organize a generic list without know the type, it will sort if its int or decimal.
However the code that retrieves the values from textboxes uses List
I tried to convert it to List, but it doesnt work.
I want this code to work if they type integers or decimals or strings in the textboxes.
This was part of an interview question where they asked not to use the sort method, and that the input should receive for example INTS or DECIMALS
private void btnSort_Click(object sender, EventArgs e)
{
List<int> list = new List<int>();
list.Add(int.Parse(i1.Text));
list.Add(int.Parse(i2.Text));
list.Add(int.Parse(i3.Text));
list.Add(int.Parse(i4.Text));
list.Add(int.Parse(i5.Text));
Sort(list);
StringBuilder sb = new StringBuilder();
foreach (int t in list)
{
sb.Append(t.ToString());
sb.AppendLine();
}
result.Text = sb.ToString();
}
private void Sort<T>(List<T> list)
{
bool madeChanges;
int itemCount = list.Count;
do
{
madeChanges = false;
itemCount--;
for (int i = 0; i < itemCount; i++)
{
int result = Comparer<T>.Default.Compare(list[i], list[i + 1]);
if (result > 0)
{
Swap(list, i, i + 1);
madeChanges = true;
}
}
} while (madeChanges);
}
public List<T> Swap<T>(List<T> list,
int firstIndex,
int secondIndex)
{
T temp = list[firstIndex];
list[firstIndex] = list[secondIndex];
list[secondIndex] = temp;
return list;
}
I wanted that something like this: but gives error
Error 1 The type or namespace name ‘T’ could not be found (are you missing a using directive or an assembly reference?) c:\users\luis.simbios\documents\visual studio 2010\Projects\InterViewPreparation1\InterViewPreparation1\Generics\GenericsSorting1.cs 22 18 InterViewPreparation1
List list = new List();
list.Add(i1.Text);
list.Add(i2.Text);
Sort(list);
In this case you can add a generic constraint
IComparable<T>and then use theCompareTo()method:Edit:
You would have to write custom code to determine whether the input is string, int or decimal, i.e. use
TryParse(..)– this will be very fragile though. Once you do know the type (one way or another) you can useMakeGenericType()andActivator.CreateInstance()to create yourList<T>object at run time and then useMakeGenericMethod()to call your generic method:I am pretty sure that is not what the interview question intended to ask for.