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

Constructor overloading in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Constructor overloading
📖 Scenario: You are creating a simple program to represent a Book in a library system. Sometimes you know all details about the book, and sometimes you only know the title.
🎯 Goal: Build a Book class with two constructors: one that takes only the title, and another that takes title, author, and year. Then create two Book objects using these constructors and print their details.
📋 What You'll Learn
Create a class called Book with three fields: title, author, and year
Add a constructor that takes only string title and sets author to "Unknown" and year to 0
Add a constructor that takes string title, string author, and int year and sets all fields
Create two Book objects: one using the single-parameter constructor and one using the three-parameter constructor
Print the details of both books in the format: Title: {title}, Author: {author}, Year: {year}
💡 Why This Matters
🌍 Real World
Constructor overloading helps create flexible classes that can be initialized with different sets of information, like creating user profiles with varying details.
💼 Career
Understanding constructor overloading is important for software developers to write clean, reusable, and flexible code in object-oriented programming.
Progress0 / 4 steps
1
Create the Book class with fields
Create a class called Book with three public fields: string title, string author, and int year.
C Sharp (C#)
Need a hint?

Use public string title; to declare the fields inside the class.

2
Add two constructors to the Book class
Add two constructors inside the Book class: one that takes string title and sets author to "Unknown" and year to 0, and another that takes string title, string author, and int year and sets all fields.
C Sharp (C#)
Need a hint?

Use this.title = title; inside each constructor to set the fields.

3
Create two Book objects using both constructors
In the Main method, create two Book objects: book1 using the constructor with only title "C# Basics", and book2 using the constructor with title "Advanced C#", author "John Doe", and year 2023.
C Sharp (C#)
Need a hint?

Use new Book("C# Basics") to create book1.

4
Print the details of both books
Add Console.WriteLine statements to print the details of book1 and book2 in the format: Title: {title}, Author: {author}, Year: {year}.
C Sharp (C#)
Need a hint?

Use Console.WriteLine($"Title: {book1.title}, Author: {book1.author}, Year: {book1.year}"); to print details.