Phase 1: Day 1-2 Exercises
Primary Constructors
Exercise 1: Basic Primary Constructor
Create a Person class using primary constructors that:
- Takes
firstName,lastName, andageparameters - Exposes
FullNameas a computed property - Has a method
Introduce()that uses the parameters
Expected behavior:
var person = new Person("John", "Doe", 30);
Console.WriteLine(person.FullName); // "John Doe"
person.Introduce(); // "Hi, I'm John Doe, 30 years old"
Exercise 2: Primary Constructor with Additional Constructor
Create a Product class with:
- Primary constructor:
Product(string name, decimal price, string category) - Additional constructor:
Product(string name, decimal price)that defaults category to "General" - Property
Nameexposed publicly - Method
Display()that shows all information
Exercise 3: Dependency Injection Pattern
Create these classes:
- Interface
ILoggerwith methodLog(string message) - Class
ConsoleLoggerimplementingILogger - Class
OrderServicewith primary constructor takingILogger - The service should log messages when processing orders
Exercise 4: Primary Constructor with Validation
Create an Email class that:
- Takes
addressas primary constructor parameter - Validates the email in the property initializer
- Throws
ArgumentExceptionfor invalid emails - Exposes
Domainproperty (e.g., "example.com" from "user@example.com")
Collection Expressions
Exercise 5: Basic Collection Expressions
Create examples using collection expressions for:
- An array of integers
- A List of strings
- A Span of doubles
- An empty collection
Exercise 6: Spread Operator
Write a method MergeArrays(int[] arr1, int[] arr2, int[] arr3) that:
- Uses collection expressions and spread operator
- Returns a single array containing all elements
- Adds 0 at the beginning and 999 at the end
Example:
int[] result = MergeArrays([1, 2], [3, 4], [5, 6]);
// Result: [0, 1, 2, 3, 4, 5, 6, 999]
Exercise 7: Conditional Collection Building
Create a method BuildConfiguration(bool includeDebug, bool includeVerbose) that:
- Returns a
List<string>with configuration flags - Always includes "Production"
- Conditionally includes "Debug" and "Verbose" based on parameters
- Uses collection expressions with spread operator
Exercise 8: Collection Types
Create a method DemonstrateCollectionTypes() that shows the same data [1, 2, 3, 4, 5] used as:
int[]List<int>Span<int>ImmutableArray<int>
Demonstrate operations on each type and explain when to use each.
Combined Exercises
Exercise 9: Event Registration System
Create an event registration system with:
Eventclass using primary constructor (name, date, maxCapacity)Attendeeclass using primary constructor (name, email)- Collection expressions to manage attendee lists
- Methods to add/remove attendees
Exercise 10: Data Aggregator
Create a DataAggregator class that:
- Has primary constructor taking
ILogger - Has method
Aggregate(List<int> cache, int[] newData, Span<int> buffer) - Uses collection expressions to combine all data sources
- Logs the aggregation process
- Returns deduplicated results
Bonus Challenges
Challenge 1: Performance Comparison
Write a benchmark comparing:
- Traditional array initialization vs collection expressions
- List initialization vs collection expressions
- Span allocation with collection expressions vs stackalloc
Challenge 2: Real-World Scenario
Build a simple shopping cart system using:
- Primary constructors for
Product,CartItem,ShoppingCart - Collection expressions for managing cart items
- Spread operator for merging saved carts
- Proper validation in constructors
Requirements:
- Add/remove items
- Calculate total
- Apply discount codes
- Merge multiple carts
- Display cart summary
Testing Your Solutions
For each exercise:
- Write the implementation
- Create test cases with various inputs
- Handle edge cases (null, empty, invalid data)
- Add XML documentation comments
Self-Assessment Questions
After completing exercises, answer:
- When should you use primary constructors vs traditional constructors?
- Do primary constructor parameters become properties automatically?
- How do collection expressions improve code readability?
- When is the spread operator useful?
- What's the performance benefit of using Span with collection expressions?
Solutions Check
Your code should demonstrate:
- ✅ Proper use of primary constructor syntax
- ✅ Understanding of parameter scope in primary constructors
- ✅ Chaining additional constructors correctly
- ✅ Using collection expressions for different collection types
- ✅ Effective use of spread operator
- ✅ Appropriate error handling and validation
- ✅ Clean, readable code following C# conventions