public int?CreateOrEditProductInMemory() { try { int productId = default; if (IsProductRepeated()) { return(default(int)); } Product productSavedInMemory = ProductsInMemory.FirstOrDefault(x => x.Id == Id); if (productSavedInMemory != null) { productSavedInMemory.Title = Title; productSavedInMemory.Number = Number; productSavedInMemory.Price = Price; // Replacing the object edited in memory according his position ProductsInMemory[ProductsInMemory.IndexOf(productSavedInMemory)] = productSavedInMemory; productId = productSavedInMemory.Id; } else { // Getting products amount for Id assignment and put them negative for avoid inconsistencies against Id from db when the user is editing Product newProduct = new Product() { Id = (ProductsInMemory.Count() + 1) * -1, Title = Title, Number = Number, Price = Price }; ProductsInMemory.Add(newProduct); productId = newProduct.Id; } memoryCache.Set(CacheKey, ProductsInMemory, CacheItemPolicy); return(productId); } catch (Exception ex) { Console.WriteLine(ex.Message); return(null); } }