.NET HELP

C# Print Function (How It Works For Developers)

Published April 3, 2024
Share:

Printing in C# is a foundational skill for developers, enabling them to communicate with users and log crucial information. The Console class is a versatile tool that offers a range of methods to cater to different scenarios. Microsoft C# programming language also provides a Print method that can be used to print to paper.

In this comprehensive article, we'll explore various aspects of C# printing, covering basic techniques, variable printing, list printing, advanced features, and an in-depth exploration of the IronPrint library.

Basic Printing with Console.WriteLine

At the core of C# printing lies the Console.WriteLine method. It's the go-to function for displaying formatted output information on the console. The simplicity of this method is evident in the following example:

Console.WriteLine("Hello, C# Print Function!"); // string line
Console.WriteLine("Hello, C# Print Function!"); // string line
Console.WriteLine("Hello, C# Print Function!") ' string line
VB   C#

This single line prints the specified string line to the console, followed by a newline character, neatly presenting the output.

Printing Variables

Printing variable values is a common requirement. C# facilitates this through string interpolation or concatenation. Here's an example illustrating variable printing:

int age = 25;
Console.WriteLine($"Age: {age}");
int age = 25;
Console.WriteLine($"Age: {age}");
Dim age As Integer = 25
Console.WriteLine($"Age: {age}")
VB   C#

In this instance, the value of the age variable is inserted into the string, providing a dynamic and informative output.

C# Print Function (How It Works For Developers): Figure 1 - Same Line Variable Output

Printing User Input

One common scenario involves printing user input to the console. Consider the following example:

Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.WriteLine($"Hello, {name}!");
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.WriteLine($"Hello, {name}!");
Console.Write("Enter your name: ")
Dim name As String = Console.ReadLine()
Console.WriteLine($"Hello, {name}!")
VB   C#

In this case, the program prompts the user for input, captures it, and then the WriteLine method prints a personalized greeting message.

Printing a List

Lists are prevalent in C# programming language, and printing their elements is a useful skill. The following code demonstrates how to print each element of a list on a new line:

List<string> fruits = new List<string> { "Apple", "Banana", "Orange" };
foreach (var fruit in fruits)
{
    Console.WriteLine(fruit);
}
List<string> fruits = new List<string> { "Apple", "Banana", "Orange" };
foreach (var fruit in fruits)
{
    Console.WriteLine(fruit);
}
Dim fruits As New List(Of String) From {"Apple", "Banana", "Orange"}
For Each fruit In fruits
	Console.WriteLine(fruit)
Next fruit
VB   C#

This loop iterates through the list and prints each fruit on a separate line.

Printing Enum Values

Enums are often used to represent a set of named constants. Printing enum values helps visualize and confirm their usage in your code:

enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }
Days today = Days.Wednesday;
Console.WriteLine($"Today is {today}");
enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }
Days today = Days.Wednesday;
Console.WriteLine($"Today is {today}");
Friend Enum Days
	Sunday
	Monday
	Tuesday
	Wednesday
	Thursday
	Friday
	Saturday
End Enum
Private today As Days = Days.Wednesday
Console.WriteLine($"Today is {today}")
VB   C#

This provides clarity on the current state of selection represented by the enum.

C# Print Function (How It Works For Developers): Figure 2 - Enum Output

Printing to Console without Newline

If you want to print text content without introducing new lines between each output, the Console.Write method is your choice. This method prevents the output from moving to the next line.

using System;
class Program
{
    public static void Main(object [] sender) // object sender
    {
        Console.Write("This ");
        Console.Write("will ");
        Console.Write("be ");
        Console.Write("on ");
        Console.Write("the ");
        Console.Write("same ");
        Console.Write("line. Even it contains more lines");
    }
}
using System;
class Program
{
    public static void Main(object [] sender) // object sender
    {
        Console.Write("This ");
        Console.Write("will ");
        Console.Write("be ");
        Console.Write("on ");
        Console.Write("the ");
        Console.Write("same ");
        Console.Write("line. Even it contains more lines");
    }
}
Imports System
Friend Class Program
	Public Shared Sub Main(ByVal sender() As Object) ' object sender
		Console.Write("This ")
		Console.Write("will ")
		Console.Write("be ")
		Console.Write("on ")
		Console.Write("the ")
		Console.Write("same ")
		Console.Write("line. Even it contains more lines")
	End Sub
End Class
VB   C#

This sequence of Write calls produces output on the same line, maintaining a cohesive presentation. This is the only difference between the Write method and the WriteLine method.

Printing with Unicode Characters

Enhance your output with Unicode characters, adding flair to your console messages. For example:

Console.WriteLine("Hello \u2665 C#");
// \u2665 represents a heart symbol
Console.WriteLine("Hello \u2665 C#");
// \u2665 represents a heart symbol
Console.WriteLine("Hello " & ChrW(&H2665).ToString() & " C#")
' \u2665 represents a heart symbol
VB   C#

Incorporating Unicode characters provides a visually appealing touch to your console output.

Debugging with Print Statements

During development, print statements are invaluable for debugging. By strategically placing Console.WriteLine statements in your code, you can output variable values or execution points to understand program flow and identify issues.

int x = 5;
int y = 10;
int sum = x + y;
Console.WriteLine($"The sum of {x} and {y} is {sum}");
int x = 5;
int y = 10;
int sum = x + y;
Console.WriteLine($"The sum of {x} and {y} is {sum}");
Dim x As Integer = 5
Dim y As Integer = 10
Dim sum As Integer = x + y
Console.WriteLine($"The sum of {x} and {y} is {sum}")
VB   C#

This aids in tracking variable values and understanding how calculations or conditions are being processed.

C# Print Function (How It Works For Developers): Figure 3 - Debugging Output

Composite Formatting

Composite string formatting allows for more dynamic and complex output. You can embed placeholders in a string and replace them with values:

double price = 19.99;
Console.WriteLine("Product: {0}, Price: ${1:F2}", "Widget", price);
double price = 19.99;
Console.WriteLine("Product: {0}, Price: ${1:F2}", "Widget", price);
Dim price As Double = 19.99
Console.WriteLine("Product: {0}, Price: ${1:F2}", "Widget", price)
VB   C#

Here, the placeholders {0} and {1} are replaced by the corresponding values, offering a flexible way to structure your output.

Formatting Date and Time

Printing the current date and time is a frequent requirement. C# provides various formatting options to display date and time information:

DateTime currentDate = DateTime.Now;
Console.WriteLine($"Current Date: {currentDate:d}");
Console.WriteLine($"Current Time: {currentDate:t}");
DateTime currentDate = DateTime.Now;
Console.WriteLine($"Current Date: {currentDate:d}");
Console.WriteLine($"Current Time: {currentDate:t}");
Dim currentDate As DateTime = DateTime.Now
Console.WriteLine($"Current Date: {currentDate:d}")
Console.WriteLine($"Current Time: {currentDate:t}")
VB   C#

Customizing the format specifier (d, t, etc.) allows developers to present the information in different ways.

Handling Exceptions with Print

When an exception occurs, printing relevant information can aid in identifying the issue. For example:

try {
      // Some code that may throw an exception
} catch (Exception ex) {
      Console.WriteLine($"Exception Caught: {ex.Message}");
}
try {
      // Some code that may throw an exception
} catch (Exception ex) {
      Console.WriteLine($"Exception Caught: {ex.Message}");
}
Try
	  ' Some code that may throw an exception
Catch ex As Exception
	  Console.WriteLine($"Exception Caught: {ex.Message}")
End Try
VB   C#

Printing the exception message assists in quickly diagnosing problems during runtime.

Advanced Printing with IronPrint: The C# Print Library

IronPrint, developed by Iron Software, is a robust and versatile printing library designed to empower .NET developers with seamless integration of printing capabilities into their applications. This comprehensive tool stands out for its compatibility across various platforms, including Windows, macOS, Android, and iOS, making it a go-to solution for developers working on diverse projects.

C# Print Function (How It Works For Developers): Figure 4 - IronPrint

One of IronPrint's key strengths lies in its broad file format support, accommodating PDF, PNG, HTML, TIFF, GIF, JPEG, and BMP. This flexibility allows developers to handle a wide array of printing requirements within their applications. Whether you are working on mobile, desktop, or console applications, IronPrint provides a unified solution for efficient and reliable printing.

IronPrint's feature set includes customizable print settings, enabling developers to tailor the printing experience to specific needs. Additionally, the library offers the option to display print dialogs, enhancing user interaction and control. The compatibility with different .NET versions and project types further contributes to its versatility, making it suitable for a variety of development scenarios.

Installation

To get started with IronPrint, install the package using NuGet:

Install-Package IronPrint

Basic Usage

Using IronPrint is straightforward. The following code prints a document using IronPrint:

using IronPrint;
Printer.Print("document.pdf");
using IronPrint;
Printer.Print("document.pdf");
Imports IronPrint
Printer.Print("document.pdf")
VB   C#

This minimal setup demonstrates the ease with which IronPrint integrates into your projects.

Print with Dialog

IronPrint extends functionality by allowing you to show a print dialog before printing:

Printer.ShowPrintDialog("document.pdf");
Printer.ShowPrintDialog("document.pdf");
Printer.ShowPrintDialog("document.pdf")
VB   C#

This feature provides users with additional control over the printing process.

Customize Print Settings

IronPrint enables you to tailor print settings according to your requirements. The following example illustrates customizing settings such as DPI, number of copies, and paper orientation:

PrintSettings printSettings = new PrintSettings();
printSettings.Dpi = 150;
printSettings.NumberOfCopies = 2;
printSettings.PaperOrientation = PaperOrientation.Portrait; Printer.Print("document.pdf", printSettings);
PrintSettings printSettings = new PrintSettings();
printSettings.Dpi = 150;
printSettings.NumberOfCopies = 2;
printSettings.PaperOrientation = PaperOrientation.Portrait; Printer.Print("document.pdf", printSettings);
Dim printSettings As New PrintSettings()
printSettings.Dpi = 150
printSettings.NumberOfCopies = 2
printSettings.PaperOrientation = PaperOrientation.Portrait
Printer.Print("document.pdf", printSettings)
VB   C#

This flexibility empowers you to fine-tune the printing process based on specific needs. For more information on IronPrint and its capabilities, please visit this documentation page.

Cross-Platform Support

IronPrint boasts compatibility with various environments, including Windows, macOS, Android, and iOS. It seamlessly integrates with .NET 8, 7, 6, 5, Core 3.1+, and .NET Framework (4.6.2+). Whether you're developing for the web, mobile, desktop, or console, IronPrint has you covered.

Conclusion

Mastering the art of printing in C# is essential for creating robust and user-friendly applications. Whether you're using the built-in capabilities of the Console class or leveraging advanced libraries like IronPrint, understanding these printing techniques is crucial. This comprehensive article has equipped you with the knowledge to print effectively in various scenarios, ensuring your applications communicate seamlessly with users and stakeholders.

While IronPrint is a paid library, free trial and its Lite package starts from $749. Download the library from here.

< PREVIOUS
C# Print Variable (How It Works For Developers)
NEXT >
C# Print a List (How It Works For Developers)

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 9,867 View Licenses >