Printing to the screen
From the syllabus
Understand the differences between string concatenation, composite formatting, and string interpolation. Practice each method to become comfortable with displaying variables in formatted output.
There are multiple ways to display content on the screen in C#. Let's explore some of the most commonly used methods:
In this example, we demonstrate three different techniques to print text to the console. Let’s break down each approach:
Understanding the Code
-
Comments:
Lines beginning with//
are comments. These lines are ignored by the compiler and serve to explain what the code is doing. Comments are invaluable for anyone reading your code, including your future self! Use comments to clarify complex logic or to note significant code sections. For multi-line comments, use the/* ... */
syntax. -
String Concatenation:
This method combines, or "concatenates," multiple strings together using the+
operator. In this example, the string"Hello "
is joined with the value of thename
variable. It’s a straightforward technique but can become cumbersome when dealing with multiple variables. -
Composite Formatting:
Here, numeric placeholders{0}
,{1}
, and{2:HH:mm}
are used inside the string. They are replaced by the variablesname
,date.DayOfWeek
, anddate
respectively, provided in the same order after the comma. This method allows for clear formatting but requires careful ordering of variables. -
String Interpolation:
This is the most modern and flexible way to format strings in C#. The$
symbol before the string allows variables to be directly embedded inside curly braces{ }
. This technique makes the code more readable and less error-prone. -
Using DateTime:
In the example above,DateTime.Now
retrieves the current date and time, storing it in thedate
variable. This allows us to display the current day and time dynamically.
Task: Experimenting with Print Methods
Modify the code to include additional information such as the user's age and the current year.
-
Declare two new variables,
age
andcurrentYear
, and assign appropriate values: -
Use all three print methods to display a message including the user’s name, age, and the current year. Add these lines to your code:
-
Run the code to observe how each method outputs the message.
Explanation of New Code
- The variable
age
is declared as anint
(integer) and assigned a value of 25. currentYear
is assigned the current year usingDateTime.Now.Year
.- Each print statement includes both the name and age variables, and each uses a different formatting method.
Conclusion
You’ve now explored three methods for printing to the console in C#. Each method has its use case and can be chosen based on the complexity and readability of the code you’re working with.