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

Instance fields and state in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Instance Fields and State in C#
📖 Scenario: Imagine you are creating a simple program to keep track of a car's details and its current speed. Each car has its own color and speed, which can change over time.
🎯 Goal: You will build a Car class with instance fields to store the car's color and speed. Then, you will create a car object, update its speed, and display its current state.
📋 What You'll Learn
Create a class called Car with instance fields color and speed
Create an object of the Car class with a specific color
Add a method to update the car's speed
Print the car's color and current speed
💡 Why This Matters
🌍 Real World
Tracking the state of objects like cars, users, or products is common in software. Instance fields store each object's unique data.
💼 Career
Understanding instance fields and object state is fundamental for programming jobs involving object-oriented design and development.
Progress0 / 4 steps
1
Create the Car class with instance fields
Create a class called Car with two instance fields: a string called color and an int called speed. Initialize speed to 0 inside the class.
C Sharp (C#)
Need a hint?

Instance fields are variables inside a class that hold data for each object.

2
Create a Car object with a color
Create a Car object called myCar and set its color field to "Red".
C Sharp (C#)
Need a hint?

Use new Car() to create an object and set the color field directly.

3
Add a method to update the speed
Inside the Car class, add a public method called SetSpeed that takes an int parameter called newSpeed and sets the instance field speed to newSpeed.
C Sharp (C#)
Need a hint?

Methods inside a class can change the instance fields to update the object's state.

4
Update speed and print car details
Use the SetSpeed method on myCar to set the speed to 60. Then, print the car's color and speed in the format: "Car color: Red, Speed: 60".
C Sharp (C#)
Need a hint?

Use the method to update speed and Console.WriteLine with an interpolated string to print.