C#
Summary - Constructor
Combine overloading and this() chaining to write a Product class.
Constructor summary
In five lessons you learned C# constructors. A constructor runs automatically with new, shares the class name, and has no return type. A parameterized constructor takes values from outside; overloading provides multiple signatures.
With this() constructors chain to each other, reducing repetition. A static constructor runs once on first use of the type and prepares type-level state. Now you will combine all of this in two mini tasks.
Exercise Add a constructor to the Counter class
Add a public int Count { get; set; } property and a parameterized constructor public Counter(int start) to the Counter class. In the body set Count = start;. Inside Main create an instance with new Counter(10) and print Count.
Show example solution
Add a property and a parameterized constructor to Counter. In Main write Counter c = new Counter(10); Console.WriteLine(c.Count);
Example solution:
using System;
class Counter
{
public int Count { get; set; }
public Counter(int start)
{
Count = start;
}
}
class Program
{
static void Main()
{
Counter c = new Counter(10);
Console.WriteLine(c.Count);
}
}
Exercise Chain with this() in Counter
The Counter class below already has public Counter(int start). Add a parameterless constructor public Counter() : this(0) { }. Inside Main create an instance with new Counter() and print Count.
Show example solution
public Counter() : this(0) { }. In Main write Counter c = new Counter(); Console.WriteLine(c.Count);
Example solution:
using System;
class Counter
{
public int Count { get; set; }
public Counter(int start)
{
Count = start;
}
public Counter() : this(0)
{
}
}
class Program
{
static void Main()
{
Counter c = new Counter();
Console.WriteLine(c.Count);
}
}
Constructors complete
Constructors are now in your toolkit. You can write parameterless or parameterized ones, single or overloaded; chain with this() to reduce repetition. A static constructor prepares type-level state.
The next group covers inheritance: how a class reuses another class's members, how to reach the base class with base, and polymorphism with virtual/override.
Test yourself
-
What does this(0, 0) do?
public Point() : this(0, 0) { }
- Assigns a static field
- Creates a new instance
- Calls another constructor in the same class
- Overrides a method
Show answer
Calls another constructor in the same class — Correct. this() chains to a constructor in the same class.
-
Complete the static constructor
class Logger { static ____() { Ready = true; } }
Show answer
class Logger { static Logger() { Ready = true; } }
Next lesson: Inheritance basics