Author: Luay Younus Version: 1.0
An Ecommerce store that demonstrates creating Array Add/Remove/AtIndex methods through Collection initializers. Xunit tests are written to prove the List resizing mechanism.
- Visual Studio 2017 Community with .NET Core 2.0 SDK
- GitBash / Terminal or GitHub Extension for Visual Studio
- Clone the repository to your local machine.
- Cd into the application directory where the
AppName.slnexist. - Open the application using
Open/Start AppName.sln. - Once Visual Studio is opened, you can Run the application by clicking on the Play button
. - A demo will be presented showing both C# built in Arrays Vs. custom array through Collection Initializers in Console statements.
public class Inventory<T> : IEnumerable<T>
public T[] Items = new T[2];
public int Count = 0;public IEnumerator<T> GetEnumerator()
{
for (int i = 0; i < Count; i++)
{
yield return Items[i];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}public void Add(T item)
{
if (Count == (Items.Length / 2))
{
T[] newArray = new T[Items.Length * 2];
for (int i = 0; i < Items.Length; i++)
{
newArray[i] = Items[i];
}
Items = newArray;
}
Items[Count] = item;
Count++;
}public void Remove(T item)
{
T[] newArray = new T[Items.Length];
if (Count - 1 <= Items.Length / 2)
{
newArray = new T[Items.Length / 2];
}
int j = 0;
int tempCount = Count;
for (int i = 0; i < tempCount; i++)
{
if (j >= tempCount) break;
if (!item.Equals(Items[j]))
{
newArray[i] = Items[j];
j++;
}
else
{
Count--;
i--;
j++;
}
}
Items = newArray;
}public int AtIndexOf(T item)
{
for (int i = 0; i < Count; i++)
{
if (Items[i].Equals(item))
{
return i;
}
}
throw new InvalidOperationException();
}public class Product
{
public string Name { get; set; }
public ProductType Type { get; set; }
public Product(string name, ProductType type)
{
Name = name;
Type = type;
}
}public enum ProductType
{
Movies,
Home,
Health,
Grocery
}[Fact]
public void Return_Equal_Inventory_Count_When_Adding()
{
// Arrange
Product product = new Product("Computer", ProductType.Home);
Inventory<Product> inventory = new Inventory<Product>();
// Act
inventory.Add(product);
// Assert
Assert.Equal(1, inventory.Count);
}
[Fact]
public void Return_Inventory_Half_Size_When_Removing()
{
// Arrange
Product product = new Product("Chair", ProductType.Home);
Inventory<Product> inventory = new Inventory<Product>();
// Act
inventory.Add(product);
inventory.Remove(product); // Resizing array to half after removing
// Assert
Assert.Equal(1, inventory.Items.Length);
}
[Fact]
public void Throw_Exception_When_Product_Not_Found()
{
// Arrange
Product product = new Product("Table", ProductType.Home);
Inventory<Product> inventory = new Inventory<Product>();
// Act & Assert
Assert.Throws<InvalidOperationException>(() => inventory.AtIndexOf(product));
}- C# Console Core application.
- Inventory Class that implements Add/Remove/AtIndex methods.
- Product Class.
- Enum for Product Types.