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

Constants and readonly fields in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Constants and readonly fields
📖 Scenario: You are creating a simple program to store information about a car. Some details about the car never change, like the number of wheels, while others can be set once when the car is created and then stay the same, like the car's model year.
🎯 Goal: Build a C# program that uses a const field for the number of wheels and a readonly field for the model year. You will see how to set these values and print them.
📋 What You'll Learn
Create a class called Car.
Add a const int field named NumberOfWheels with the value 4.
Add a readonly int field named ModelYear.
Create a constructor for Car that takes an int parameter to set ModelYear.
Create a method DisplayInfo that prints the number of wheels and model year.
In Main, create a Car object with model year 2023 and call DisplayInfo.
💡 Why This Matters
🌍 Real World
Constants and readonly fields are used in programs to keep important values safe from accidental changes, like fixed settings or initial data.
💼 Career
Understanding constants and readonly fields is important for writing reliable and maintainable code in many software development jobs.
Progress0 / 4 steps
1
Create the Car class with a const field
Create a class called Car and inside it, declare a const int field named NumberOfWheels and set it to 4.
C Sharp (C#)
Need a hint?

Use public const int NumberOfWheels = 4; inside the Car class.

2
Add a readonly field and constructor
Inside the Car class, add a readonly int field named ModelYear. Then create a constructor for Car that takes an int modelYear parameter and sets the ModelYear field.
C Sharp (C#)
Need a hint?

Use public readonly int ModelYear; and set it inside the constructor.

3
Add a method to display car info
Inside the Car class, add a method called DisplayInfo that prints the number of wheels and the model year using Console.WriteLine. Use the fields NumberOfWheels and ModelYear.
C Sharp (C#)
Need a hint?

Use Console.WriteLine with the fields inside DisplayInfo.

4
Create a Car object and show info
In the Main method, create a Car object named myCar with model year 2023. Then call myCar.DisplayInfo() to print the details.
C Sharp (C#)
Need a hint?

Create the object with new Car(2023) and call DisplayInfo().