Complete the code to call the default constructor from the parameterized constructor.
public class Car { public Car() { Console.WriteLine("Default constructor called"); } public Car(string model) : [1] { Console.WriteLine($"Car model: {model}"); } }
In C#, this() calls another constructor in the same class, enabling constructor chaining.
Complete the code to chain constructors so the parameterless constructor calls the parameterized one.
public class Book { public Book(string title) { Console.WriteLine($"Title: {title}"); } public Book() : [1] { Console.WriteLine("No title provided"); } }
The parameterless constructor calls the parameterized one with a default value using this("Unknown").
Fix the error in constructor chaining by completing the code.
public class Person { public Person(string name) { Console.WriteLine($"Name: {name}"); } public Person() : [1] { Console.WriteLine("No name given"); } }
The parameterless constructor must call the parameterized one with a string argument, so this(null) is correct.
Fill both blanks to chain constructors correctly and print the age.
public class Animal { public Animal(string species, int age) { Console.WriteLine($"Species: {species}, Age: {age}"); } public Animal(string species) : [1] { Console.WriteLine($"Species only: {species}"); } public Animal() : [2] { Console.WriteLine("No details provided"); } }
The constructor with one parameter calls the two-parameter constructor with age 0 using this(species, 0). The parameterless constructor calls the two-parameter constructor with "Unknown" and age 0 using this("Unknown", 0).
Fill all three blanks to chain constructors and initialize all fields.
public class Employee { public string Name; public int Id; public string Department; public Employee(string name, int id, string department) { Name = name; Id = id; Department = department; Console.WriteLine($"Name: {Name}, Id: {Id}, Department: {Department}"); } public Employee(string name, int id) : [1] { Console.WriteLine("Department set to General"); } public Employee(string name) : [2] { Console.WriteLine("Id set to 0 and Department to General"); } public Employee() : [3] { Console.WriteLine("Default employee created"); } }
Each constructor calls the three-parameter constructor with default values to chain initialization properly: the two-parameter constructor calls the three-parameter one with "General" department using this(name, id, "General"), the one-parameter constructor calls the three-parameter one with id 0 and "General" using this(name, 0, "General"), and the parameterless constructor calls the three-parameter one with "Unknown", 0, and "General" using this("Unknown", 0, "General").