.NET HELP

C# Print Variable: Simplify Your Code

Published April 3, 2024
Share:

Printing variables in C# is an essential skill for any developer. Whether you are debugging your code, displaying information to users, or simply checking the state of your program, the Console.WriteLine statement is your go-to tool for standard output stream operations. The Console class from the namespace System provides the Write and WriteLine method for printing variable values on the console window.

In this comprehensive article, we will explore various aspects of printing variables in C#, covering different data types, formatting options, and advanced techniques.

Basic Variable Printing

We can easily print numeric values using the Console.WriteLine method as shown in the below code example.

int integerValue = 42; // specified value
Console.WriteLine($"Integer Value: {integerValue}"); // standard output stream
int integerValue = 42; // specified value
Console.WriteLine($"Integer Value: {integerValue}"); // standard output stream
Dim integerValue As Integer = 42 ' specified value
Console.WriteLine($"Integer Value: {integerValue}") ' standard output stream
VB   C#

In this basic example, we declare an integer variable (integerValue) and use the Console.WriteLine statement to print the specified value to the console. The $ symbol before the string allows us to embed the variable directly into the string literal using string interpolation.

String Variable Printing

string greeting = "Hello, C#!";
Console.WriteLine($"Greeting: {greeting}");
string greeting = "Hello, C#!";
Console.WriteLine($"Greeting: {greeting}");
Dim greeting As String = "Hello, C#!"
Console.WriteLine($"Greeting: {greeting}")
VB   C#

Printing string variables follows the same pattern. We declare a string variable (greeting), assign a string value("Hello, C#!"), and use Console.WriteLine for output. This is useful for displaying messages or any textual information.

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

If you want to print variables values on same line then you can use Console.Write method. The only difference between both the methods is that WriteLine leave a new line character at the end so the next output is printed on the next line and Write method prints everything on the same line.

Multiple Variables in a Single Line

int x = 5, y = 10;
Console.WriteLine($"X: {x}, Y: {y}");
int x = 5, y = 10;
Console.WriteLine($"X: {x}, Y: {y}");
Dim x As Integer = 5, y As Integer = 10
Console.WriteLine($"X: {x}, Y: {y}")
VB   C#

You can print multiple variables in a single line by separating them with commas within the string. This is beneficial for displaying related information together.

C# Print Variable (How It Works For Developers): Figure 2 - Multiple Variables in Single line Output

Formatting Variables

double piValue = Math.PI;
Console.WriteLine($"Approximate Value of Pi: {piValue:F5}");
double piValue = Math.PI;
Console.WriteLine($"Approximate Value of Pi: {piValue:F5}");
Dim piValue As Double = Math.PI
Console.WriteLine($"Approximate Value of Pi: {piValue:F5}")
VB   C#

Formatting becomes crucial, especially for floating-point numbers. Here, the F5 format specifier ensures that the value of Pi is printed with five digits after the decimal point.

Concatenating Variables

int apples = 3, oranges = 5;
Console.WriteLine("Total Fruits: " + (apples + oranges));
int apples = 3, oranges = 5;
Console.WriteLine("Total Fruits: " + (apples + oranges));
Dim apples As Integer = 3, oranges As Integer = 5
Console.WriteLine("Total Fruits: " & (apples + oranges))
VB   C#

String Concatenation can be used for more complex output. Here, the total number of fruits is calculated and printed in on the same line.

Printing Variable Types

bool isTrue = true;
Console.WriteLine($"Is True? {isTrue}, Variable Type: {isTrue.GetType()}");
bool isTrue = true;
Console.WriteLine($"Is True? {isTrue}, Variable Type: {isTrue.GetType()}");
Dim isTrue As Boolean = True
Console.WriteLine($"Is True? {isTrue}, Variable Type: {isTrue.GetType()}")
VB   C#

Sometimes, it's beneficial to display not just the variable default value but also the type of the variable. The GetType() method accomplishes this.

Advanced Techniques for Printing variables

Using String.Format

int width = 10, height = 5;
string formattedOutput = String.Format("Dimensions: {0} x {1}", width, height); Console.WriteLine(formattedOutput);
int width = 10, height = 5;
string formattedOutput = String.Format("Dimensions: {0} x {1}", width, height); Console.WriteLine(formattedOutput);
Dim width As Integer = 10, height As Integer = 5
Dim formattedOutput As String = String.Format("Dimensions: {0} x {1}", width, height)
Console.WriteLine(formattedOutput)
VB   C#

The String.Format method provides another way to format strings and print variables, offering more control over the output structure.

Verbatim String Literal

string filePath = @"C:\MyDocuments\file.txt";
Console.WriteLine($"File Path: {filePath}");
string filePath = @"C:\MyDocuments\file.txt";
Console.WriteLine($"File Path: {filePath}");
Dim filePath As String = "C:\MyDocuments\file.txt"
Console.WriteLine($"File Path: {filePath}")
VB   C#

For paths or strings with escape characters, verbatim string literals (prefixed with @) can be used to simplify the code. Here, string formatting helps to print the file path with ease.

Console Output Control

Redirecting Console Output

The following code example helps you write the console window output to a file:

using System;
using System.IO;
class Program
{
// public static void Main
    public static void Main(string [] args)
    {
        string outputPath = "output.txt";
        using (StreamWriter sw = new StreamWriter(outputPath))
        {
            Console.SetOut(sw);
            Console.WriteLine("This will be written to the file.");
        }
    }
}
using System;
using System.IO;
class Program
{
// public static void Main
    public static void Main(string [] args)
    {
        string outputPath = "output.txt";
        using (StreamWriter sw = new StreamWriter(outputPath))
        {
            Console.SetOut(sw);
            Console.WriteLine("This will be written to the file.");
        }
    }
}
Imports System
Imports System.IO
Friend Class Program
' public static void Main
	Public Shared Sub Main(ByVal args() As String)
		Dim outputPath As String = "output.txt"
		Using sw As New StreamWriter(outputPath)
			Console.SetOut(sw)
			Console.WriteLine("This will be written to the file.")
		End Using
	End Sub
End Class
VB   C#

Redirecting console output to a file allows you to capture and save the output for further analysis or logging purposes.

Console Colors

Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("This text will be displayed in red.");
Console.ResetColor(); // Reset color to default
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("This text will be displayed in red.");
Console.ResetColor(); // Reset color to default
Console.ForegroundColor = ConsoleColor.Red
Console.WriteLine("This text will be displayed in red.")
Console.ResetColor() ' Reset color to default
VB   C#

Changing the console text color adds visual emphasis to specific output, making it easier to differentiate between different types of information.

IronPrint: Empowering .NET Developers with Advanced Printing Capabilities

IronPrint is a powerful print library developed by Iron Software. IronPrint is a comprehensive print library designed to seamlessly integrate with .NET applications. IronPrint stands as a reliable and feature-rich printing library for .NET developers. Its cross-platform compatibility, support for various document formats, and customizable settings make it a valuable tool for handling diverse printing tasks. Whether you're developing for desktop, mobile, or web applications, IronPrint provides a versatile solution to meet your printing needs in the ever-evolving landscape of .NET development.

C# Print Variable (How It Works For Developers): Figure 3 - IronPrint

It provides a range of features that empower developers to handle diverse printing requirements, from basic document printing to customizable settings and cross-platform compatibility.

Key Features

  1. Format Support: IronPrint supports a variety of document formats, including PDF, PNG, HTML, TIFF, GIF, JPEG, and BITMAP. This versatility ensures that developers can work with different types of content for printing.
  2. Customizable Settings: Developers have the flexibility to customize print settings according to their application's requirements. This includes options to set DPI (dots per inch), specify paper orientation (portrait or landscape), and control the number of copies.
  3. Print Dialog: IronPrint facilitates a seamless user experience by allowing developers to show a print dialog before printing. This can be useful in scenarios where users need to interact with the printing process and select specific options.

Compatibility and Installation

IronPrint boasts extensive compatibility across different .NET versions, making it accessible to a wide range of developers. It supports .NET 8, 7, 6, 5, and Core 3.1+, as well as the .NET Framework (4.6.2+). The library caters to various project types, including a mobile (Xamarin, MAUI), desktop (WPF, MAUI, Windows Avalonia), and Console applications.

Installation

To get started with IronPrint, developers can quickly install the library using NuGet Package Manager.

Install-Package IronPrint

Alternatively, the package can be downloaded directly from the official IronPrint NuGet website or by NuGet Package Manager for Solutions.

Applying License Key

Before utilizing IronPrint functionalities, developers need to apply a valid license or trial key. This involves assigning the license key to the LicenseKey property of the License class. The following code snippet demonstrates this step:

using IronPrint; 
// Apply license key
License.LicenseKey = "IRONPRINT.MYLICENSE.KEY.1EF01";
using IronPrint; 
// Apply license key
License.LicenseKey = "IRONPRINT.MYLICENSE.KEY.1EF01";
Imports IronPrint
' Apply license key
License.LicenseKey = "IRONPRINT.MYLICENSE.KEY.1EF01"
VB   C#

Code Examples

Print Document

To print a document using IronPrint, developers can simply pass the file path to the Print method:

using IronPrint;
// Print the document
Printer.Print("newDoc.pdf");
using IronPrint;
// Print the document
Printer.Print("newDoc.pdf");
Imports IronPrint
' Print the document
Printer.Print("newDoc.pdf")
VB   C#

Print With Dialog

For scenarios where a print dialog is desirable, the ShowPrintDialog method can be used:

using IronPrint;
// Show print dialog
Printer.ShowPrintDialog("newDoc.pdf");
using IronPrint;
// Show print dialog
Printer.ShowPrintDialog("newDoc.pdf");
Imports IronPrint
' Show print dialog
Printer.ShowPrintDialog("newDoc.pdf")
VB   C#

Customize Print Settings

To configure print settings programmatically, developers can instantiate the PrintSettings class:

using IronPrint;
// Configure print setting
PrintSettings printSettings = new PrintSettings();
printSettings.Dpi = 150;
printSettings.NumberOfCopies = 2;
printSettings.PaperOrientation = PaperOrientation.Portrait;
// Print the document with custom settings
Printer.Print("newDoc.pdf", printSettings);
using IronPrint;
// Configure print setting
PrintSettings printSettings = new PrintSettings();
printSettings.Dpi = 150;
printSettings.NumberOfCopies = 2;
printSettings.PaperOrientation = PaperOrientation.Portrait;
// Print the document with custom settings
Printer.Print("newDoc.pdf", printSettings);
Imports IronPrint
' Configure print setting
Private printSettings As New PrintSettings()
printSettings.Dpi = 150
printSettings.NumberOfCopies = 2
printSettings.PaperOrientation = PaperOrientation.Portrait
' Print the document with custom settings
Printer.Print("newDoc.pdf", printSettings)
VB   C#

For more coding examples please visit this code example page.

Conclusion

Printing variables in C# is a fundamental skill that every developer should master. The Console.WriteLine statement, combined with various formatting techniques such as string concatenation, string literals, and string interpolation, provides a flexible and effective way to output variable values. As you explore more complex scenarios, such as working with different data types and advanced formatting options, you'll enhance your ability to communicate information effectively within your C# programs.

IronPrint is a paid library, but developers can explore its features using free trial licenses. For more information, developers can visit the official documentation and API Reference page. Download the library from here and give it a try.

< PREVIOUS
How to Use C# Print Line Effectively
NEXT >
Master C# Print Function: A Developer’s Guide

Ready to get started? Version: 2024.12 just released

Free NuGet Download Total downloads: 12,923 View Licenses >