Console.WriteLine

Standard .NET console output method. Simplest logging means available immediately without configuration. Suitable for rapid output verification during development and debugging stages, but functionality limited in production environments. Optimal for prototyping.

Logging LibraryC#.NETConsoleDebugStandard

Library

Console.WriteLine

Overview

Console.WriteLine is the standard .NET console output method, serving as the simplest logging means in C# development. It provides the most basic log output functionality available immediately without configuration, ideal for rapid output verification during development and debugging stages. Supporting string interpolation, format strings, and composite formatting capabilities, it's perfect for prototyping and learning phases. While its functionality is limited for full-scale application development, migration to dedicated logging libraries is strongly recommended.

Details

Console.WriteLine has been provided as a standard method in the System namespace since the early days of .NET Framework, and its use in learning and prototyping stages remains unchanged even in 2025. It's fully integrated with C# 11+ string interpolation features ($""), raw string literals, and complex formatting with multiple dollar signs, maintaining high compatibility with modern C# syntax. It enables output window display in Visual Studio integrated development environment and real-time confirmation during debugging sessions. While usage continues among .NET beginners and simple console applications, migration to dedicated libraries such as Microsoft.Extensions.Logging, Serilog, and NLog has become the industry standard for full-scale application development.

Key Features

  • .NET standard inclusion: Immediate use without additional installation
  • String interpolation support: Complete support for C# 11+ latest syntax
  • Formatting capabilities: Flexible use of composite formatting and string interpolation
  • Visual Studio integration: Direct output confirmation in development environment
  • Lightweight: Zero overhead simple I/O operations
  • Minimal learning cost: Ideal introduction tool for C# beginners

Advantages and Disadvantages

Advantages

  • Standard position in .NET ecosystem with complete absence of learning cost
  • Immediate usage start without configuration/initialization improving development efficiency
  • Modern writing experience through complete integration with C# string interpolation features
  • Excellent integration and debugging experience with Visual Studio development environment
  • Zero impact on other libraries due to lightweight implementation
  • Ideal simplicity for prototyping and proof of concept

Disadvantages

  • Complete lack of functionality limitations and log management/monitoring capabilities in production environments
  • Absence of log levels, filtering, and categorization functionality
  • Impossibility of file output, database recording, and external service integration
  • Performance constraints during high load due to synchronous I/O operations
  • Limitations in structured logging, JSON output, and analytics tool integration
  • Insufficient functionality for enterprise requirements

Reference Pages

Code Examples

Basic String Output

using System;

class Program
{
    static void Main()
    {
        // Basic string output
        Console.WriteLine("Hello, World!");
        Console.WriteLine("Application has started");
        
        // Variable output
        string userName = "John Doe";
        int userAge = 30;
        bool isActive = true;
        
        Console.WriteLine(userName);
        Console.WriteLine(userAge);
        Console.WriteLine(isActive);
        
        // Multi-line output
        Console.WriteLine("First line");
        Console.WriteLine("Second line");
        Console.WriteLine("Third line");
        
        // Empty line output
        Console.WriteLine();
        Console.WriteLine("Message after empty line");
    }
}

String Interpolation

using System;

class Program
{
    static void Main()
    {
        // Basic string interpolation
        string name = "John Doe";
        int age = 30;
        decimal salary = 85000.50m;
        DateTime joinDate = new DateTime(2020, 4, 1);
        
        Console.WriteLine($"Name: {name}");
        Console.WriteLine($"Age: {age} years old");
        Console.WriteLine($"Salary: {salary:C}");
        Console.WriteLine($"Join Date: {joinDate:yyyy/MM/dd}");
        
        // Embedding complex expressions
        Console.WriteLine($"Next year's age: {age + 1} years old");
        Console.WriteLine($"Years of experience: {DateTime.Now.Year - joinDate.Year} years");
        Console.WriteLine($"Status: {(age >= 30 ? "Senior" : "Junior")}");
        
        // Using format specifiers
        double value = 123.456789;
        Console.WriteLine($"2 decimal places: {value:F2}");
        Console.WriteLine($"Percentage display: {0.85:P}");
        Console.WriteLine($"Scientific notation: {value:E}");
        Console.WriteLine($"Hexadecimal: {255:X}");
        
        // Combination with conditional operators
        int score = 85;
        Console.WriteLine($"Grade: {score} points ({(score >= 80 ? "Excellent" : score >= 60 ? "Pass" : "Fail")})");
        
        // Embedding method calls
        Console.WriteLine($"Current time: {DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")}");
        Console.WriteLine($"Random value: {new Random().Next(1, 100)}");
    }
}

C# 11+ Raw String Literals

using System;

class Program
{
    static void Main()
    {
        // Basic raw string literal
        string sqlQuery = """
            SELECT u.Name, u.Age, d.DepartmentName
            FROM Users u
            INNER JOIN Departments d ON u.DepartmentId = d.Id
            WHERE u.IsActive = 1
            ORDER BY u.Name
            """;
        
        Console.WriteLine("SQL Query:");
        Console.WriteLine(sqlQuery);
        
        // Interpolated raw string literal
        string tableName = "Users";
        int minAge = 25;
        
        string dynamicQuery = $$"""
            SELECT *
            FROM {{tableName}}
            WHERE Age >= {{minAge}}
            AND IsActive = 1
            """;
        
        Console.WriteLine($"Dynamic Query:");
        Console.WriteLine(dynamicQuery);
        
        // JSON template example
        string userName = "John Doe";
        int userId = 123;
        
        string jsonTemplate = $$"""
            {
                "userId": {{userId}},
                "userName": "{{userName}}",
                "settings": {
                    "theme": "dark",
                    "language": "en"
                },
                "permissions": ["read", "write"]
            }
            """;
        
        Console.WriteLine("JSON Template:");
        Console.WriteLine(jsonTemplate);
        
        // Complex text formatting
        string projectName = "WebApp";
        string version = "1.2.3";
        DateTime buildDate = DateTime.Now;
        
        string buildInfo = $$"""
            ┌─────────────────────────────────────┐
            │            Build Info               │
            ├─────────────────────────────────────┤
            │ Project:      {{projectName}}                │
            │ Version:      {{version}}                   │
            │ Build Date:   {{buildDate:yyyy/MM/dd HH:mm}} │
            └─────────────────────────────────────┘
            """;
        
        Console.WriteLine(buildInfo);
    }
}

Composite Formatting

using System;

class Program
{
    static void Main()
    {
        // Basic composite formatting
        string name = "John Doe";
        int age = 30;
        decimal salary = 85000.50m;
        
        Console.WriteLine("Name: {0}, Age: {1}, Salary: {2:C}", name, age, salary);
        
        // Reusing position specifiers
        Console.WriteLine("{0} is {1} years old. {0}'s salary is {2:C}.", name, age, salary);
        
        // Width specification and alignment
        Console.WriteLine("Name: {0,-20} Age: {1,3} Salary: {2,12:C}", name, age, salary);
        
        // More complex formatting example
        var employees = new[]
        {
            new { Name = "John Doe", Age = 30, Salary = 85000.50m },
            new { Name = "Jane Smith", Age = 28, Salary = 78000.00m },
            new { Name = "Bob Johnson", Age = 35, Salary = 92000.75m }
        };
        
        Console.WriteLine("Employee List:");
        Console.WriteLine("{0,-15} {1,5} {2,12}", "Name", "Age", "Salary");
        Console.WriteLine(new string('-', 35));
        
        foreach (var emp in employees)
        {
            Console.WriteLine("{0,-15} {1,5} {2,12:C}", emp.Name, emp.Age, emp.Salary);
        }
        
        // Custom format provider
        var englishProvider = new System.Globalization.CultureInfo("en-US");
        Console.WriteLine("English locale: {0:C}", 123456.78, englishProvider);
        
        // Date/time formatting
        DateTime now = DateTime.Now;
        Console.WriteLine("Current time: {0:yyyy/MM/dd HH:mm:ss}", now);
        Console.WriteLine("Short date: {0:d}", now);
        Console.WriteLine("Long date: {0:D}", now);
        Console.WriteLine("ISO format: {0:yyyy-MM-ddTHH:mm:ss}", now);
    }
}

Debugging and Troubleshooting

using System;
using System.Collections.Generic;
using System.Diagnostics;

class Program
{
    static void Main()
    {
        // Conditional compilation
        #if DEBUG
        Console.WriteLine("Running in debug mode");
        #endif
        
        // Detailed output for debugging
        var userData = new
        {
            Id = 123,
            Name = "John Doe",
            Email = "[email protected]",
            CreatedAt = DateTime.Now.AddDays(-30)
        };
        
        Console.WriteLine("=== User Data ===");
        Console.WriteLine($"ID: {userData.Id}");
        Console.WriteLine($"Name: {userData.Name}");
        Console.WriteLine($"Email: {userData.Email}");
        Console.WriteLine($"Created: {userData.CreatedAt:yyyy/MM/dd}");
        
        // Exception information output
        try
        {
            int divisor = 0;
            int result = 10 / divisor;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception occurred:");
            Console.WriteLine($"  Type: {ex.GetType().Name}");
            Console.WriteLine($"  Message: {ex.Message}");
            Console.WriteLine($"  Stack Trace:");
            Console.WriteLine(ex.StackTrace);
        }
        
        // Processing time measurement
        var stopwatch = Stopwatch.StartNew();
        
        // Simulate time-consuming process
        System.Threading.Thread.Sleep(100);
        
        stopwatch.Stop();
        Console.WriteLine($"Processing time: {stopwatch.ElapsedMilliseconds}ms");
        
        // Memory usage display
        long memoryBefore = GC.GetTotalMemory(false);
        Console.WriteLine($"Memory usage: {memoryBefore:N0} bytes");
        
        // Collection content display
        var numbers = new List<int> { 1, 2, 3, 4, 5 };
        Console.WriteLine($"Array content: [{string.Join(", ", numbers)}]");
        
        // Detailed object display
        var person = new Person { Name = "John Doe", Age = 30 };
        Console.WriteLine($"Person object: {person}");
    }
}

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    
    public override string ToString()
    {
        return $"Name={Name}, Age={Age}";
    }
}

Advanced Formatting Techniques

using System;
using System.Globalization;
using System.Text;

class Program
{
    static void Main()
    {
        // Detailed numeric format control
        decimal value = 1234567.89m;
        
        Console.WriteLine("=== Numeric Formatting ===");
        Console.WriteLine($"Currency: {value:C}");
        Console.WriteLine($"Fixed point: {value:F2}");
        Console.WriteLine($"Exponential: {value:E2}");
        Console.WriteLine($"Number: {value:N2}");
        Console.WriteLine($"Percent: {0.1234:P2}");
        Console.WriteLine($"Zero padding: {123:D8}");
        Console.WriteLine($"Hexadecimal: {255:X4}");
        
        // Custom numeric format
        Console.WriteLine($"Custom1: {value:#,##0.00}");
        Console.WriteLine($"Custom2: {value:$#,##0}");
        Console.WriteLine($"Conditional: {-123:positive;negative;zero}");
        
        // Detailed date/time formatting
        DateTime dateTime = new DateTime(2025, 6, 24, 14, 30, 45);
        
        Console.WriteLine("\n=== Date/Time Formatting ===");
        Console.WriteLine($"Standard: {dateTime}");
        Console.WriteLine($"Short date: {dateTime:d}");
        Console.WriteLine($"Long date: {dateTime:D}");
        Console.WriteLine($"Short time: {dateTime:t}");
        Console.WriteLine($"Long time: {dateTime:T}");
        Console.WriteLine($"Full: {dateTime:F}");
        Console.WriteLine($"ISO 8601: {dateTime:yyyy-MM-ddTHH:mm:ss}");
        Console.WriteLine($"Custom: {dateTime.ToString("MMMM dd, yyyy", new CultureInfo("en-US"))}");
        
        // TimeSpan formatting
        var timeSpan = new TimeSpan(1, 2, 3, 4, 567);
        Console.WriteLine($"\nTimeSpan: {timeSpan:d\\d\\ hh\\:mm\\:ss\\.fff}");
        
        // Complex object display
        var product = new
        {
            Id = 12345,
            Name = "Smartphone",
            Price = 89800m,
            InStock = true,
            Categories = new[] { "Electronics", "Communication", "Mobile" },
            Specifications = new Dictionary<string, object>
            {
                { "OS", "Android 14" },
                { "RAM", "8GB" },
                { "Storage", "256GB" }
            }
        };
        
        Console.WriteLine("\n=== Product Information ===");
        Console.WriteLine($"Product ID: {product.Id}");
        Console.WriteLine($"Product Name: {product.Name}");
        Console.WriteLine($"Price: {product.Price:C}");
        Console.WriteLine($"In Stock: {(product.InStock ? "Yes" : "No")}");
        Console.WriteLine($"Categories: {string.Join(" > ", product.Categories)}");
        
        Console.WriteLine("Specifications:");
        foreach (var spec in product.Specifications)
        {
            Console.WriteLine($"  {spec.Key}: {spec.Value}");
        }
        
        // StringBuilder usage for performance consideration
        var sb = new StringBuilder();
        sb.AppendLine("=== Report ===");
        
        for (int i = 1; i <= 5; i++)
        {
            sb.AppendLine($"Item {i}: Value {i * 10}");
        }
        
        Console.WriteLine(sb.ToString());
        
        // Error message formatting
        string errorCode = "E001";
        string errorMessage = "Database connection error";
        string details = "Connection timeout occurred";
        
        Console.WriteLine($"\n❌ Error [{errorCode}]: {errorMessage}");
        Console.WriteLine($"   Details: {details}");
        Console.WriteLine($"   Time: {DateTime.Now:yyyy/MM/dd HH:mm:ss}");
    }
}

Practical Logging Patterns

using System;
using System.IO;
using System.Runtime.CompilerServices;

class Program
{
    private static readonly string LogFilePath = "application.log";
    
    static void Main()
    {
        // Simple logging functionality implementation
        LogInfo("Application started");
        
        try
        {
            ProcessData();
            LogInfo("Data processing completed");
        }
        catch (Exception ex)
        {
            LogError("Data processing error", ex);
        }
        finally
        {
            LogInfo("Application terminated");
        }
    }
    
    static void ProcessData()
    {
        LogDebug("Data processing started");
        
        // Data processing simulation
        for (int i = 1; i <= 3; i++)
        {
            LogInfo($"Step {i} executing");
            System.Threading.Thread.Sleep(500); // Processing time simulation
        }
        
        // Warning example
        LogWarning("Some data may be outdated");
        
        LogDebug("Data processing finished");
    }
    
    // Log level enumeration
    enum LogLevel
    {
        Debug,
        Info,
        Warning,
        Error
    }
    
    // Basic log method
    static void Log(LogLevel level, string message, Exception exception = null,
        [CallerMemberName] string memberName = "",
        [CallerFilePath] string sourceFilePath = "",
        [CallerLineNumber] int sourceLineNumber = 0)
    {
        var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
        var fileName = Path.GetFileName(sourceFilePath);
        var logMessage = $"[{timestamp}] [{level.ToString().ToUpper()}] {message}";
        
        if (exception != null)
        {
            logMessage += $"\n  Exception: {exception.Message}";
            logMessage += $"\n  StackTrace: {exception.StackTrace}";
        }
        
        // Console output (color coding)
        var originalColor = Console.ForegroundColor;
        Console.ForegroundColor = GetLogColor(level);
        Console.WriteLine(logMessage);
        Console.ForegroundColor = originalColor;
        
        // File output (optional)
        try
        {
            File.AppendAllText(LogFilePath, logMessage + Environment.NewLine);
        }
        catch
        {
            // Ignore file write errors
        }
        
        // Debug information (debug mode only)
        #if DEBUG
        if (level >= LogLevel.Warning)
        {
            Console.WriteLine($"  Source: {fileName}:{sourceLineNumber} in {memberName}()");
        }
        #endif
    }
    
    static ConsoleColor GetLogColor(LogLevel level)
    {
        return level switch
        {
            LogLevel.Debug => ConsoleColor.Gray,
            LogLevel.Info => ConsoleColor.White,
            LogLevel.Warning => ConsoleColor.Yellow,
            LogLevel.Error => ConsoleColor.Red,
            _ => ConsoleColor.White
        };
    }
    
    // Convenience methods for each log level
    static void LogDebug(string message) => Log(LogLevel.Debug, message);
    static void LogInfo(string message) => Log(LogLevel.Info, message);
    static void LogWarning(string message) => Log(LogLevel.Warning, message);
    static void LogError(string message, Exception ex = null) => Log(LogLevel.Error, message, ex);
    
    // Structured log simulation
    static void LogStructured(string eventName, object data)
    {
        var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
        Console.WriteLine($"[{timestamp}] [EVENT] {eventName}");
        
        if (data != null)
        {
            var properties = data.GetType().GetProperties();
            foreach (var prop in properties)
            {
                var value = prop.GetValue(data);
                Console.WriteLine($"  {prop.Name}: {value}");
            }
        }
    }
}