I'm trying to implement Sorting trash container. Unfortunately, I'm not so experienced in C# yet and I'm obviously not getting the point of handling the generic method and corresponding interfaces. Below is some part of my code.
static void RandomNumbers()
{
Random random = new Random((int)DateTime.Now.Ticks);
SortedTrashContainer<int> trash = new SortedTrashContainer<int>(10);
for (int i = 0; i < trash.Capacity; i++)
trash.Add(random.Next(10));
Console.WriteLine("== Random numbers ==");
foreach (var item in trash)
Console.Write(item + " ");
}
class SortedTrashContainer<T> where T : IContainer<T>, IComparable<T>
{
private int size;
private int pointer = 0;
private T[] items;
public int Capacity => size;
public SortedTrashContainer(int capacity)
{
if (capacity >= 0)
{
size = capacity;
items = new T[capacity];
}
else
throw new ArgumentOutOfRangeException();
}
public void Add(T item)
{
if (pointer < size)
{
items[pointer++] = item;
Sort(items);
}
else
throw new InvalidOperationException();
}
private void Sort(T[] array)
{
int top = array.Length - 1;
int indexOfLargest;
do
{
indexOfLargest = 0;
for (int i = 0; i <= top; i++)
{
if (array[indexOfLargest].CompareTo(array[i]) < 0)
indexOfLargest = i;
}
IComparable temp = (IComparable)array[top];
array[top] = array[indexOfLargest];
array[indexOfLargest] = (T)temp;
top--;
} while (top > 0);
}
}
In the line where I declare an object trash
with the reference to SortedTrashContainer
and passing an int
type as parameter I'm getting compilation error "The type 'int' cannot be used as type parameter T in the generic method SortedTrashContainer<T>
. There is no boxing conversion from int
to MyNameSpace.IContainer<int>
". Unfortunately I'm really stuck here. Just not getting the point, what can resolve this issue.