C#C
C#11mo ago
Faker

Feedback on small code exercises

C#
class CustomList<T>
{
    private T[] items;
    private int size;
    
    public CustomList()
    {
        items = new T[10];
        size = 0;
    }

    // Add method
    public void Add(T item)
    {
        // Check if resizing is needed
        if (size >= items.Length)
        {
            // Array.Resize(ref items, size * 2);
            Resize();
        }

        // Add item
        items[size] = item;
        size++;
    }

    public void PrintArray()
    {
        foreach (var item in items)
        {
            Console.Write(item + " ");
        }
    }
    
    
    // Remove method
    public void Remove(T item)
    {
        var indexResult = Array.IndexOf(items, item);
        if (indexResult != -1)
        {
            // item exist - should be removed
            for (int i = indexResult; i <= size; i++)
            {
                // Shift all elements after the found index to the left
                (items[indexResult], items[i]) = (items[i], items[indexResult]);
            }
            
            // Set the last element to default(T) and decrease the size
            items[size] = default(T);
            size--;
        }
        else
        {
            Console.WriteLine("item doesn't exist");
        }

    }

     private void Resize()
    {
        // Double the capacity
        var newCapacity = items.Length * 2;
        // Create a new larger array
        var newArray = new T[newCapacity];
        for (int i = 0; i < newArray.Length; i++)
        {
            newArray[i] = default(T);
        }
        // Copy old elements into the new array
        var counter = 0;
        foreach (var item in items)
        {
            newArray[counter] = item;
            counter++;
        }
        // Reassign the items array to the new array
        items = newArray;
    }

}
Was this page helpful?