Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
Printing lines in C# is a fundamental aspect of console applications, and it involves displaying text or specified values on the console screen. Whether you're working with the standard output stream or formatting strings, understanding how to print lines efficiently is crucial in C# Console Applications.
In this article, we'll explore various methods and techniques related to printing lines in C#.
In C#, printing a line often involves using the Console.WriteLine method. Let's start by looking at a simple example:
using System;
class Program {
public static void Main() {
Console.WriteLine("Hello, C# Print Line!");
}
}
using System;
class Program {
public static void Main() {
Console.WriteLine("Hello, C# Print Line!");
}
}
Imports System
Friend Class Program
Public Shared Sub Main()
Console.WriteLine("Hello, C# Print Line!")
End Sub
End Class
In the above code, the Console.WriteLine statement outputs the specified string value ("Hello, C# Print Line!") followed by a new line. This is achieved by the WriteLine method, which appends a line terminator to the end of the output.
A line terminator is a special character or sequence that indicates the end of a line. The two most common line terminators are the carriage return ('\r') and line feed ('\n'). In C#, the Console.WriteLine method takes care of using the appropriate current line terminator based on the operating system.
public static void Main() {
Console.WriteLine("This is on the first line.");
Console.WriteLine("This is on the second line.");
}
public static void Main() {
Console.WriteLine("This is on the first line.");
Console.WriteLine("This is on the second line.");
}
Public Shared Sub Main()
Console.WriteLine("This is on the first line.")
Console.WriteLine("This is on the second line.")
End Sub
In the example above, after the program execution, each Console.WriteLine produces a new line in the C# console window, resulting in the two specified lines.
If you need to control the line terminator explicitly, you can use the Console.Write method and add the desired line terminator manually:
public static void Main() {
Console.Write("This is on the first line.");
Console.Write('\r'); // Carriage return
Console.Write("This is on the same line but very far left position.");
}
public static void Main() {
Console.Write("This is on the first line.");
Console.Write('\r'); // Carriage return
Console.Write("This is on the same line but very far left position.");
}
Imports Microsoft.VisualBasic
Public Shared Sub Main()
Console.Write("This is on the first line.")
Console.Write(ControlChars.Cr) ' Carriage return
Console.Write("This is on the same line but very far left position.")
End Sub
In this example, the carriage return ('\r') is used to position the cursor at the beginning of the line, resulting in the second part of the text appearing at the far-left position i.e. overwriting the previous output.
To print multiple lines without repeating the Console.WriteLine statement, you can use a variable length parameter list:
public static void Main() {
PrintLines("Line 1", "Line 2", "Line 3");
}
static void PrintLines(params string [] lines) {
foreach (var line in lines) {
Console.WriteLine(line);
}
}
public static void Main() {
PrintLines("Line 1", "Line 2", "Line 3");
}
static void PrintLines(params string [] lines) {
foreach (var line in lines) {
Console.WriteLine(line);
}
}
Public Shared Sub Main()
PrintLines("Line 1", "Line 2", "Line 3")
End Sub
Shared Sub PrintLines(ParamArray ByVal lines() As String)
For Each line In lines
Console.WriteLine(line)
Next line
End Sub
The PrintLines method we have created takes a specified array of string parameters, allowing you to pass any number of new lines to print a specified string value:
Formatting output is crucial, especially when dealing with different data types. The Console.WriteLine method provides several overloads that accept a specified object and format information:
public static void Main() {
int answer = 42;
string name = "John Doe";
Console.WriteLine("The answer is {0}.", answer);
Console.WriteLine("Hello, {0}!", name);
}
public static void Main() {
int answer = 42;
string name = "John Doe";
Console.WriteLine("The answer is {0}.", answer);
Console.WriteLine("Hello, {0}!", name);
}
Public Shared Sub Main()
Dim answer As Integer = 42
Dim name As String = "John Doe"
Console.WriteLine("The answer is {0}.", answer)
Console.WriteLine("Hello, {0}!", name)
End Sub
In this example, {0} is a placeholder for the specified objects (in this case, answer and name), allowing you to include variable data in the output and print the specified format information.
For special line breaks or Unicode characters, you can use escape sequences. You can also print any ASCII literal or valid HTML code using Console.WriteLine. For example, to include a one-line break in the same string:
public static void Main() {
Console.WriteLine("This is line 1.\nThis is line 2.");
Console.WriteLine("Line 1\u000Aline 2");
}
public static void Main() {
Console.WriteLine("This is line 1.\nThis is line 2.");
Console.WriteLine("Line 1\u000Aline 2");
}
Imports Microsoft.VisualBasic
Public Shared Sub Main()
Console.WriteLine("This is line 1." & vbLf & "This is line 2.")
Console.WriteLine("Line 1" & vbLf & "line 2")
End Sub
Here, \n and \u000A, the specified Unicode character, both represent a line feed character, causing the text to move to the next line in each case.
The below code uses string interpolation in the Console.WriteLine method. String interpolation is a feature introduced in C# 6.0 that simplifies the process of embedding expressions or variables within string literals and displaying the specified boolean value on the Console application properly.
Random rnd = new Random();
for (int i = 1; i <= 5; i++)
{
bool isTrue = rnd.Next(0, 2) == 1;
Console.WriteLine($"True or False: {isTrue}");
}
Random rnd = new Random();
for (int i = 1; i <= 5; i++)
{
bool isTrue = rnd.Next(0, 2) == 1;
Console.WriteLine($"True or False: {isTrue}");
}
Dim rnd As New Random()
For i As Integer = 1 To 5
Dim isTrue As Boolean = rnd.Next(0, 2) = 1
Console.WriteLine($"True or False: {isTrue}")
Next i
The specified data returned from the expression is printed on the console application as shown below:
Printing various numeric formats is a common requirement in programming, especially when dealing with double-precision floating-point and single-precision floating-point numbers. Again, the Console.WriteLine statements can be utilized to print them with precision and ease.
double doubleValue = 0.123456789;
Console.WriteLine($"Double Precision: {doubleValue:F7}");
double doubleValue = 0.123456789;
Console.WriteLine($"Double Precision: {doubleValue:F7}");
Dim doubleValue As Double = 0.123456789
Console.WriteLine($"Double Precision: {doubleValue:F7}")
In this example, F7 specifies that the double value should be formatted with 7 digits after the decimal point. You can adjust the number after 'F' to control the precision.
string existingString = "Hello, C#!";
Console.WriteLine($"Existing String: {existingString}");
string existingString = "Hello, C#!";
Console.WriteLine($"Existing String: {existingString}");
Dim existingString As String = "Hello, C#!"
Console.WriteLine($"Existing String: {existingString}")
Printing an existing string is straightforward. Simply use Console.WriteLine and include the string you want to display.
float singleValue = 0.123456789f;
Console.WriteLine($"Single Precision: {singleValue:F7}");
float singleValue = 0.123456789f;
Console.WriteLine($"Single Precision: {singleValue:F7}");
Dim singleValue As Single = 0.123456789F
Console.WriteLine($"Single Precision: {singleValue:F7}")
Similar to double precision, the F7 format specifier is used here for single-precision floating-point. You can adjust the number after 'F' based on your precision requirements.
Printing documents is a fundamental aspect of many applications, and when it comes to harnessing the full potential of printing in C#, IronPrint stands out as a versatile and feature-rich library.
IronPrint, developed by Iron Software, is an advanced print library designed for the .NET ecosystem, including C#. Whether you are working on a desktop, mobile, or web application, IronPrint seamlessly integrates with your C# projects, providing a comprehensive set of tools for handling diverse printing needs.
1. Cross-Platform Compatibility:
IronPrint supports various operating systems, including Windows, macOS, Android, and iOS. This cross-platform compatibility ensures that your printing solutions can reach users across different environments.
2. .NET Version Support:
Compatible with .NET Framework 4.6.2 and above, .NET Core 3.1+, and the latest .NET versions, IronPrint covers a wide range of .NET environments.
3. Project Type Support:
IronPrint caters to different project types, including Mobile (Xamarin & MAUI), Desktop (WPF & MAUI), and Console (App & Library). This flexibility makes it suitable for a variety of application architectures.
4. Easy Installation:
Getting started with IronPrint is a breeze. You can quickly install the library by using the NuGet Package Manager Console and executing the Install-Package IronPrint command.
Here's a simple example demonstrating how easy it is to use IronPrint in a C# console application to print documents:
using IronPrint;
class Program
{
static void Main()
{
Console.WriteLine("Printing Started...");
// Silent printing of a document
Printer.Print("document.pdf");
// Or display a print dialog
Printer.ShowPrintDialog("document.pdf");
Console.WriteLine("Printing Completed...");
}
}
using IronPrint;
class Program
{
static void Main()
{
Console.WriteLine("Printing Started...");
// Silent printing of a document
Printer.Print("document.pdf");
// Or display a print dialog
Printer.ShowPrintDialog("document.pdf");
Console.WriteLine("Printing Completed...");
}
}
Imports IronPrint
Friend Class Program
Shared Sub Main()
Console.WriteLine("Printing Started...")
' Silent printing of a document
Printer.Print("document.pdf")
' Or display a print dialog
Printer.ShowPrintDialog("document.pdf")
Console.WriteLine("Printing Completed...")
End Sub
End Class
The output here shows the printing of a document using the Print and ShowPrintDialog method. If the physical printer is not installed then the default printer is used for printing.
IronPrint goes beyond basic printing tasks and offers advanced features such as:
IronPrint allows you to tailor your printing solutions for different platforms. For example, when working with .NET Core projects targeting specific platforms like Windows, Android, iOS, or macOS, you can adjust the TargetFrameworks property in your project file accordingly.
To get more detailed information on IronPrint, please visit this documentation and API reference pages.
Printing lines in C# is a foundational skill for console application development. Whether you're displaying text, formatting output, or controlling line terminators, understanding the various techniques available will enhance your ability to create effective and readable console programs. Explore the diverse methods provided by the Console class, experiment with formatting options, and leverage the flexibility of C# to produce clear and well-structured console output in your applications.
IronPrint emerges as a powerful ally for C# developers seeking robust and flexible printing capabilities. With its cross-platform support, compatibility with various .NET versions, and advanced printing features, IronPrint simplifies the implementation of printing solutions in diverse C# applications. Whether you're developing for desktop, mobile, or web, IronPrint provides the tools you need to bring your printing requirements to life in the world of C# development.
IronPrint offers a free trial for commercial use. Download the library from here and give it a try.
9 .NET API products for your office documents