.NET HELP

C# Print Statement: Learn the Basics

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()
    {
        // Print a greeting message to the console
        Console.WriteLine("Hello, C# Print Statement!");
    }
}
using System;

class Program
{
    public static void Main()
    {
        // Print a greeting message to the console
        Console.WriteLine("Hello, C# Print Statement!");
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		' Print a greeting message to the console
		Console.WriteLine("Hello, C# Print Statement!")
	End Sub
End Class
$vbLabelText   $csharpLabel

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()
    {
        // Define a string message and an integer number
        string message = "Welcome to C#";
        int number = 42;

        // Print the message and number to the console
        Console.WriteLine(message);
        Console.WriteLine("The answer is: " + number);
    }
}
using System;

class Program
{
    public static void Main()
    {
        // Define a string message and an integer number
        string message = "Welcome to C#";
        int number = 42;

        // Print the message and number to the console
        Console.WriteLine(message);
        Console.WriteLine("The answer is: " + number);
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		' Define a string message and an integer number
		Dim message As String = "Welcome to C#"
		Dim number As Integer = 42

		' Print the message and number to the console
		Console.WriteLine(message)
		Console.WriteLine("The answer is: " & number)
	End Sub
End Class
$vbLabelText   $csharpLabel

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()
    {
        // Initialize variables
        string name = "John";
        int age = 30;

        // Use placeholders for string formatting
        Console.WriteLine("Name: {0}, Age: {1}", name, age);

        // Use string interpolation for a cleaner approach
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}
using System;

class Program
{
    public static void Main()
    {
        // Initialize variables
        string name = "John";
        int age = 30;

        // Use placeholders for string formatting
        Console.WriteLine("Name: {0}, Age: {1}", name, age);

        // Use string interpolation for a cleaner approach
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		' Initialize variables
		Dim name As String = "John"
		Dim age As Integer = 30

		' Use placeholders for string formatting
		Console.WriteLine("Name: {0}, Age: {1}", name, age)

		' Use string interpolation for a cleaner approach
		Console.WriteLine($"Name: {name}, Age: {age}")
	End Sub
End Class
$vbLabelText   $csharpLabel

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
$vbLabelText   $csharpLabel

Customizing Formatting

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

using System;

class Program
{
    public static void Main()
    {
        // Get the current date
        DateTime currentDate = DateTime.Now;

        // Print the current date in a long date pattern
        Console.WriteLine("Today is {0:D}", currentDate);
    }
}
using System;

class Program
{
    public static void Main()
    {
        // Get the current date
        DateTime currentDate = DateTime.Now;

        // Print the current date in a long date pattern
        Console.WriteLine("Today is {0:D}", currentDate);
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		' Get the current date
		Dim currentDate As DateTime = DateTime.Now

		' Print the current date in a long date pattern
		Console.WriteLine("Today is {0:D}", currentDate)
	End Sub
End Class
$vbLabelText   $csharpLabel

Composite Formatting

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

using System;

class Program
{
    public static void Main()
    {
        // Define a price and character array
        double price = 19.99;
        char[] chars = { 'A', 'B', 'C' };

        // Format the output string using placeholders
        Console.WriteLine("Product: {0}, Price: ${1:F2} | Characters: {2}", 
                          "Widget", price, new string(chars));
    }
}
using System;

class Program
{
    public static void Main()
    {
        // Define a price and character array
        double price = 19.99;
        char[] chars = { 'A', 'B', 'C' };

        // Format the output string using placeholders
        Console.WriteLine("Product: {0}, Price: ${1:F2} | Characters: {2}", 
                          "Widget", price, new string(chars));
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		' Define a price and character array
		Dim price As Double = 19.99
		Dim chars() As Char = { "A"c, "B"c, "C"c }

		' Format the output string using placeholders
		Console.WriteLine("Product: {0}, Price: ${1:F2} | Characters: {2}", "Widget", price, New String(chars))
	End Sub
End Class
$vbLabelText   $csharpLabel

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 line, but you can use Console.Write method to print on the same line, as shown in the following example:

using System;

class Program
{
    public static void Main()
    {
        // Print parts of a sentence on the same line
        Console.Write("This ");
        Console.Write("is ");
        Console.Write("on ");
        Console.WriteLine("the same line.");
    }
}
using System;

class Program
{
    public static void Main()
    {
        // Print parts of a sentence on the same line
        Console.Write("This ");
        Console.Write("is ");
        Console.Write("on ");
        Console.WriteLine("the same line.");
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		' Print parts of a sentence on the same line
		Console.Write("This ")
		Console.Write("is ")
		Console.Write("on ")
		Console.WriteLine("the same line.")
	End Sub
End Class
$vbLabelText   $csharpLabel

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 the 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;

class PrintExample
{
    public static void Main()
    {
        // Print a document
        Printer.Print("newDoc.pdf");

        // Show a print dialog for user interaction
        Printer.ShowPrintDialog("newDoc.pdf");

        // Customize print settings
        PrintSettings printSettings = new PrintSettings
        {
            Dpi = 150,
            NumberOfCopies = 2,
            PaperOrientation = PaperOrientation.Portrait
        };

        // Print using the customized settings
        Printer.Print("newDoc.pdf", printSettings);
    }
}
using IronPrint;

class PrintExample
{
    public static void Main()
    {
        // Print a document
        Printer.Print("newDoc.pdf");

        // Show a print dialog for user interaction
        Printer.ShowPrintDialog("newDoc.pdf");

        // Customize print settings
        PrintSettings printSettings = new PrintSettings
        {
            Dpi = 150,
            NumberOfCopies = 2,
            PaperOrientation = PaperOrientation.Portrait
        };

        // Print using the customized settings
        Printer.Print("newDoc.pdf", printSettings);
    }
}
Imports IronPrint

Friend Class PrintExample
	Public Shared Sub Main()
		' Print a document
		Printer.Print("newDoc.pdf")

		' Show a print dialog for user interaction
		Printer.ShowPrintDialog("newDoc.pdf")

		' Customize print settings
		Dim printSettings As New PrintSettings With {
			.Dpi = 150,
			.NumberOfCopies = 2,
			.PaperOrientation = PaperOrientation.Portrait
		}

		' Print using the customized settings
		Printer.Print("newDoc.pdf", printSettings)
	End Sub
End Class
$vbLabelText   $csharpLabel

For more detailed information on IronPrint and its capabilities as a printing hub, please visit the documentation 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 there is a free trial available.

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

Frequently Asked Questions

What is the C# print statement used for?

The C# print statement is used to output information to the console, facilitating communication between the program and the user. It is essential for displaying messages, data, or results of operations and is commonly used for debugging and user interaction.

How do you use the Console.WriteLine method in C#?

In C#, the Console.WriteLine method is used to print a specified string or value to the console, followed by a new line. It is part of the Console class within the System namespace.

Can you print variables and their values using the Console.WriteLine method?

Yes, you can print variables and their values using the Console.WriteLine method by including them as parameters within the method.

What are some ways to format output in C#?

C# provides various ways to format output, including using placeholders and string interpolation. These methods allow you to insert variable values into a formatted string.

What is IronPrint and how is it used?

IronPrint is a comprehensive print library developed by Iron Software for .NET developers. It allows printing of physical documents and supports various file formats and environments. It is installed using the NuGet Package Manager.

What environments does IronPrint support?

IronPrint supports multiple environments, including Windows, macOS, iOS, and Android. It is compatible with .NET versions 8, 7, 6, 5, and Core 3.1+.

How can you customize print settings with IronPrint?

With IronPrint, you can customize print settings such as DPI, number of copies, and paper orientation using the PrintSettings class.

Is there a free trial available for IronPrint?

Yes, IronPrint offers a free trial. More details can be found on their licensing page.

Chaknith Bin
Software Engineer
Chaknith works on IronXL and IronBarcode. He has deep expertise in C# and .NET, helping improve the software and support customers. His insights from user interactions contribute to better products, documentation, and overall experience.
< PREVIOUS
C# Print Console: Step-by-Step Guide

Ready to get started? Version: 2025.6 just released

View Licenses >