.NET HELP

C# Print Statement (How It Works For Developers)

Updated March 27, 2024
Share:

Printing is a fundamental aspect of application development, allowing developers to communicate with users through the console or physical documents. In C#, the print statement is a versatile tool for displaying information, and in this article, we'll explore its usage, options, and best practices.

Introduction to C# Print Statement

The print statement is used to output information to the console in C#. It facilitates communication between the program and the user, providing a way to display messages, data, or results of operations. The statement is essential for debugging, user interaction, and general information output during program execution.

Basic Syntax

The basic syntax of the print statement in C# involves using the Console.WriteLine method, which automatically adds a new line after the specified string or value. The Console class, nestled within the System namespace, incorporates the WriteLine method, employed for outputting information to the standard output stream. This method operates with both the string line having multiple variables and user input acquired via the standard input stream.

Here's a simple example:

using System;
class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello, C# Print Statement!");
    }
}
using System;
class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello, C# Print Statement!");
    }
}
Imports System
Friend Class Program
	Public Shared Sub Main()
		Console.WriteLine("Hello, C# Print Statement!")
	End Sub
End Class
VB   C#

In this simple example, the Console class's WriteLine method is used to print the specified string to the console, followed by a new line.

Printing Variables and Values

You can print the string literals and numeric values of variables by including them as parameters in the Console.WriteLine method. For example:

using System;
class Program
{
    public static void Main()
    {
        string message = "Welcome to C#";
        int number = 42;
        Console.WriteLine(message);
        Console.WriteLine("The answer is: " + number);
    }
}
using System;
class Program
{
    public static void Main()
    {
        string message = "Welcome to C#";
        int number = 42;
        Console.WriteLine(message);
        Console.WriteLine("The answer is: " + number);
    }
}
Imports System
Friend Class Program
	Public Shared Sub Main()
		Dim message As String = "Welcome to C#"
		Dim number As Integer = 42
		Console.WriteLine(message)
		Console.WriteLine("The answer is: " & number)
	End Sub
End Class
VB   C#

Here the above code example shows how the values of the message and number variables are printed to the console using WriteLine method.

C# Print Statement (How It Works For Developers): Figure 1 - Console.WriteLine Output

Special Characters and String Formatting

C# provides various ways to format output using placeholders or string interpolation. Check the following example:

using System;
class Program
{
    public static void Main()
    {
        string name = "John";
        int age = 30;
        Console.WriteLine("Name: {0}, Age: {1}", name, age);
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}
using System;
class Program
{
    public static void Main()
    {
        string name = "John";
        int age = 30;
        Console.WriteLine("Name: {0}, Age: {1}", name, age);
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}
Imports System
Friend Class Program
	Public Shared Sub Main()
		Dim name As String = "John"
		Dim age As Integer = 30
		Console.WriteLine("Name: {0}, Age: {1}", name, age)
		Console.WriteLine($"Name: {name}, Age: {age}")
	End Sub
End Class
VB   C#

Both approaches achieve the same result, allowing you to insert variable values into a formatted string.

Additional Formatting Options

Line Terminator

By default, the line terminator is "\r\n" (carriage return + line feed). You can change it using:

Console.Out.NewLine = "\n";
// Set to newline character only
Console.Out.NewLine = "\n";
// Set to newline character only
Imports Microsoft.VisualBasic

Console.Out.NewLine = vbLf
' Set to newline character only
VB   C#

Customizing Formatting

The format string allows customization with placeholders and formatting options. For instance:

DateTime currentDate = DateTime.Now;
Console.WriteLine("Today is {0:D}", currentDate);
DateTime currentDate = DateTime.Now;
Console.WriteLine("Today is {0:D}", currentDate);
Dim currentDate As DateTime = DateTime.Now
Console.WriteLine("Today is {0:D}", currentDate)
VB   C#

Composite Formatting

Here's an example of composite formatting and printing a character array on one line:

double price = 19.99;
char[] chars = { 'A', 'B', 'C' };
Console.WriteLine("Product: {0}, Price: ${1:F2} | Characters: {2}", "Widget", price, new string(chars));
double price = 19.99;
char[] chars = { 'A', 'B', 'C' };
Console.WriteLine("Product: {0}, Price: ${1:F2} | Characters: {2}", "Widget", price, new string(chars));
Dim price As Double = 19.99
Dim chars() As Char = { "A"c, "B"c, "C"c }
Console.WriteLine("Product: {0}, Price: ${1:F2} | Characters: {2}", "Widget", price, New String(chars))
VB   C#

In this code example, the product name and price are formatted using composite formatting, and the characters are printed as a string using new string(chars).

New Line and Line Breaks

Controlling new lines and line breaks is crucial for structuring output. The Console.WriteLine method automatically adds a new next line, but you can use Console.Write method. The only difference is that this method prints on the same line in console window, as shown in the following example:

using System;
class Program
{
    public static void Main()
    {
        Console.Write("This ");
        Console.Write("is ");
        Console.Write("on ");
        Console.WriteLine("the same line.");
    }
}
using System;
class Program
{
    public static void Main()
    {
        Console.Write("This ");
        Console.Write("is ");
        Console.Write("on ");
        Console.WriteLine("the same line.");
    }
}
Imports System
Friend Class Program
	Public Shared Sub Main()
		Console.Write("This ")
		Console.Write("is ")
		Console.Write("on ")
		Console.WriteLine("the same line.")
	End Sub
End Class
VB   C#

The above code example produces the print output: "This is on the same line."

IronPrint: Your All-in-One Print Library for .NET

IronPrint, developed by Iron Software, is a comprehensive print library designed for .NET developers to print physical documents. It offers a wide range of features and supports various environments, making it a versatile solution for printing documents in C# applications. If the physical printer is not available then it uses the default printer as its default value for printing the document.

C# Print Statement (How It Works For Developers): Figure 2 - IronPrint for .NET: The C# Printing Library

Installation

IronPrint can be installed using the NuGet Package Manager console or using the Visual Studio Package Manager.

To install IronPrint using the NuGet Package Manager Console, use the following command:

Install-Package IronPrint

Alternatively, you can install it in your project using Visual Studio. Right-click on Solution Explorer and click Manage NuGet Package Manager for Solutions. In NuGet browse tab, search for IronPrint and then click install to add it to your project:

C# Print Statement (How It Works For Developers): Figure 3 - Install IronPrint using NuGet Package Manager by searching "ironprint" in the search bar of NuGet Package Manager, then selecting the project and clicking the Install button.

Why Consider IronPrint?

1. Cross-Platform Magic

Whether you're working on Windows, macOS, iOS, or Android, IronPrint has your back. It works well with .NET versions 8, 7, 6, 5, and Core 3.1+, making it incredibly versatile.

2. Format Flexibility

From PDF to PNG, HTML, TIFF, GIF, JPEG, IMAGE, and BITMAP – IronPrint handles it all.

3. Print Settings

Allows customization of print settings, including DPI, number of copies, paper orientation, etc.

4. Easy Installation

Installing IronPrint is a snap. Just use NuGet Package Manager Console and type the command: Install-Package IronPrint, and you're good to go.

How Does It Work?

Printing with IronPrint is a walk in the park. Take a look at this quick code example where you can easily print with a dialog and control print settings:

using IronPrint;
// Print a document
Printer.Print("newDoc.pdf");
// Show a print dialog
Printer.ShowPrintDialog("newDoc.pdf");
// Customize print settings
PrintSettings printSettings = new PrintSettings();
printSettings.Dpi = 150;
printSettings.NumberOfCopies = 2;
printSettings.PaperOrientation = PaperOrientation.Portrait;
Printer.Print("newDoc.pdf", printSettings);
using IronPrint;
// Print a document
Printer.Print("newDoc.pdf");
// Show a print dialog
Printer.ShowPrintDialog("newDoc.pdf");
// Customize print settings
PrintSettings printSettings = new PrintSettings();
printSettings.Dpi = 150;
printSettings.NumberOfCopies = 2;
printSettings.PaperOrientation = PaperOrientation.Portrait;
Printer.Print("newDoc.pdf", printSettings);
Imports IronPrint
' Print a document
Printer.Print("newDoc.pdf")
' Show a print dialog
Printer.ShowPrintDialog("newDoc.pdf")
' Customize print settings
Dim printSettings As New PrintSettings()
printSettings.Dpi = 150
printSettings.NumberOfCopies = 2
printSettings.PaperOrientation = PaperOrientation.Portrait
Printer.Print("newDoc.pdf", printSettings)
VB   C#

For more detailed information on IronPrint and its capabilities as a Printing hub, please visit the documentation page. To get more familiar with the API, please visit this API Reference page.

Conclusion

The print statement in C# is a powerful tool for communicating with users, displaying information, and debugging code. Whether you're a beginner or an experienced developer, understanding how to use the Console.WriteLine method effectively is essential for creating informative and user-friendly applications.

IronPrint is your go-to printing library if you want accuracy, ease of use, and speed. Whether you're building WebApps, working with MAUI, Avalonia, or anything .NET-related, IronPrint has got your back.

IronPrint is a paid library, but free trial page.

Ready to make your life as a developer a bit easier? Get IronPrint from here!

< PREVIOUS
C# Print to Console (How It Works For Developers)

Ready to get started? Version: 2024.5 just released

Start Free Trial Total downloads: 3,233
View Licenses >