Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
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.
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
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 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}")
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.
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.
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}")
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.
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}")
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.
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))
String Concatenation can be used for more complex output. Here, the total number of fruits is calculated and printed in on the same line.
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()}")
Sometimes, it's beneficial to display not just the variable default value but also the type of the variable. The GetType() method accomplishes this.
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)
The String.Format method provides another way to format strings and print variables, offering more control over the output structure.
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}")
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.
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
Redirecting console output to a file allows you to capture and save the output for further analysis or logging purposes.
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
Changing the console text color adds visual emphasis to specific output, making it easier to differentiate between different types of information.
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.
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.
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.
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.
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"
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")
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")
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)
For more coding examples please visit this code example page.
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.
9 .NET API products for your office documents