0
0
C Sharp (C#)programming~30 mins

Common bugs from reference sharing in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Common Bugs from Reference Sharing in C#
📖 Scenario: Imagine you are working on a simple inventory system for a small store. You have a list of products, and you want to create a copy of this list to apply discounts without changing the original list.This project will help you understand how sharing references between objects can cause unexpected bugs.
🎯 Goal: You will create a list of products, then create a copy of this list. You will apply a discount to the copied list and observe how changes affect the original list due to reference sharing.
📋 What You'll Learn
Create a list of products with exact names and prices
Create a copy of the product list by assigning it to a new variable
Apply a discount to the copied list by changing product prices
Print both original and copied lists to observe the effect of reference sharing
💡 Why This Matters
🌍 Real World
Understanding reference sharing helps prevent bugs in programs that manage collections of objects, like inventory systems, user lists, or game entities.
💼 Career
Many programming jobs require managing data structures carefully to avoid unintended side effects from shared references, especially in object-oriented languages like C#.
Progress0 / 4 steps
1
Create the original product list
Create a list called products containing three Product objects with these exact values: ("Apple", 100), ("Banana", 50), and ("Cherry", 75). Use the provided Product class.
C Sharp (C#)
Need a hint?

Use new List<Product> { ... } and add three new Product(name, price) objects inside the braces.

2
Create a copy of the product list by reference
Create a new variable called discountedProducts and assign it the value of products (this copies the reference, not the objects).
C Sharp (C#)
Need a hint?

Just assign discountedProducts = products; to copy the reference.

3
Apply a discount to the copied list
Use a for loop with variable i to go through discountedProducts and reduce each product's Price by 10%. Use integer division for simplicity.
C Sharp (C#)
Need a hint?

Use a for loop from 0 to discountedProducts.Count and update the Price by multiplying by 90 and dividing by 100.

4
Print both lists to observe the effect
Use two foreach loops to print the Name and Price of each product in products and discountedProducts. Print "Original products:" before the first list and "Discounted products:" before the second list.
C Sharp (C#)
Need a hint?

Use Console.WriteLine to print the headers and product details. Notice that both lists show the discounted prices because they share the same references.