Loading...

C# Generics

Write one class that can hold a string or an int, and let the caller name which. The class is Hold<T>. T stands in for the type. Hold<string> holds the word pine. Hold<int> holds the number 12. dotnet run prints pine, then 12. Two lines. No x between them.
The example changes here. The program-arguments file printed left=10 right=2 sum=12, then 2026-03-05, then pine x12, and the word came from args[0]. Leave that file's Add, Label, date, and Main(string[] args) out of this one. If dotnet run --no-build still shows pine x12, you are running the old program. This page's screen is the word and the number on separate lines, and the word is written in the constructor, not on the command line.

One class, a type you fill in

Open the PineLab project. You may replace the body of the old file. Keep the project folder so dotnet run still finds the .csproj. The entry point stays a class named Pine with Main(). The new class sits above it.
Hold is not a list. The list page already used List<int>, which is a generic somebody else wrote. This page writes the generic. One holder stores one value.
The class takes a type argument in angle brackets. The field uses that type. The constructor receives one value of that type and stores it:
public class Hold<T>
public T Item;
public Hold(T item)
Item = item;
T is not a variable you assign later. It is decided where you construct the object. Item is PascalCase because it is a public field. item is camelCase because it is a parameter. They are different names, the same habit as left and Left on the naming page.
In Main, build two holders and print each field:
Hold<string> word = new Hold<string>("pine");
Hold<int> number = new Hold<int>(12);
Console.WriteLine(word.Item);
Console.WriteLine(number.Item);
Main has empty parentheses. It does not take string[] args.

Hold stores a string and an int

csharp
using System;

public class Hold<T>
{
    public T Item;

    public Hold(T item)
    {
        Item = item;
    }
}

public class Pine
{
    public static void Main()
    {
        Hold<string> word = new Hold<string>("pine");
        Hold<int> number = new Hold<int>(12);
        Console.WriteLine(word.Item);
        Console.WriteLine(number.Item);
    }
}

Two lines, not a label

From the PineLab folder, run dotnet run. The screen shows pine, then 12. dotnet run compiles when the source is newer, then starts Pine.Main. The build report is not the lesson screen. The lesson screen is the two lines after it.
Walk Main once. The first line constructs a Hold<string> and stores the four letters pine in Item. The second constructs a Hold<int> and stores the int 12. The first WriteLine prints the string. The second prints the int. Nothing joins them. Nothing writes x. Nothing reads args.
The 12 is a literal in this file. It is the same number the old label used, written out on purpose so you can see it alone. Add is not in this file, so a minus cannot turn the second line into 8. If the second line is 8, you are not running this file.
A command left over from the last page does not feed this Main. dotnet run -- pine still prints pine then 12, and the word after -- is ignored, because Main() takes no arguments. The pine you see is the one inside new Hold<string>("pine").

The brackets are the type

Hold<string> and Hold<int> are two uses of one class. The code of Hold is written once. The type argument changes what Item is. On the string holder, Item is a string. On the int holder, Item is an int. You did not copy the class into HoldString and HoldInt. The brackets did that job.
Write the type on new as well: new Hold<string>("pine"). C# does not fill those brackets in from the left when you leave them empty. new Hold<>("pine") does not compile. Put string back between the brackets.
T itself is only the placeholder inside the class. You do not construct new Hold<T> in Main. You construct Hold<string> or Hold<int>. Outside the class, T is not a type you can name.
A public field is read with a dot: word.Item. The local is word. The field is Item. Printing word without .Item prints the holder, not the stored word. The checked lines print Item.

A mismatch fails before Main

new Hold<string>(12) does not compile. 12 is an int. The constructor of Hold<string> wants a string. The build stops, and neither line appears, because Main never starts. Change it back to "pine".
new Hold<int>("pine") stops the same way. A string is not an int. There is no silent conversion inside Hold. The class does not parse text, and it does not call ToString for you when the types differ.
C# does not let you skip the argument and keep a plain Hold. Hold word = new Hold("pine"); fails the build. The type argument is required. Some other languages let a list run with the brackets left off. This file is C#. Leave the brackets on.
The list page was the other direction. List<int> asked you to fill in <int> on a class the framework already had. You stored 3 and 8 and printed 3 then 2. You can still do that on that page. You do not paste that bag into this file. Here the class under the brackets is yours.

📊 What Hold accepts

Kind What the build allows
String Hold<string> stores "pine" and Item is a string
Int Hold<int> stores 12 and Item is an int
Mismatch new Hold<string>(12) fails the build and prints nothing

What stays out of the file

This file is two classes and two prints. It has no Add, no Label, no DateTime, no Random, and no ReadLine. Those were real tools. They are not what a generic holder needs. Putting the date back would add a third line and hide the pair you are checking.
It also has no constraint. You will see where T : class in other code. That limits which types are allowed. This page allows any T the caller names, and the only limit is the one at the constructor: the value must match that T. Do not add where.
Do not add a second Main. Pine.Main is the entry. Hold has a constructor, not an entry point. Two entry points fail the build with no screen.

The old screen is a different program

If you need the sum, the date, and pine x12 again, that is the program-arguments file, and it is still the end of the core path. This page did not delete it from the course. It only uses a different file so the holder is the whole story. Switching back is a matter of which source dotnet run compiles. Do not try to make one Main print both screens. You will not be able to tell which lesson you are on.
dotnet run --no-build on a project you have not rebuilt since the arguments page shows the old three lines. That is the stale build from the compiling page, still true. dotnet run without --no-build compiles first. Use that command for the check.
The core path is already complete. This page is optional. Nothing here turns is_completed off. You can stop after the arguments page and still have finished the core.

Lambda stays shut

You can store pine in Hold<string>, store 12 in Hold<int>, and print those two lines. You can see a wrong value fail the build. The next page is lambda. It writes a small function without a name. This page stops before that. There is no => in this file. Hold is a class with a constructor, not a function you pass around.
One last pass: one Hold<T>, field Item, constructor stores item, Main() takes no arguments, new Hold<string>("pine"), new Hold<int>(12), both prints use .Item, you are in PineLab, and dotnet run shows pine then 12. When those two lines match, generics did their job.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
4
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top