Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio
C#

Step-by-Step: Building a Modern Console App with C# 13

- 23.08.26 - ErcanOPAK

🎯 Key Takeaways: Build a modern console application using C# 13 features. Includes primary constructors, params collections, and more.

Console apps aren’t dead. C# 13 makes them better than ever.

🚀 Create Project

# Create console app with .NET 9 (C# 13 support)
dotnet new console -n ModernConsole
cd ModernConsole

# Enable C# 13 features
dotnet add package Microsoft.Net.Compilers.Toolset --version 4.9.0

💡 Program.cs

using ModernConsole.Models;
using ModernConsole.Services;

// ✅ C# 13: Top-level statements with primary constructor
var app = new ConsoleApp(args);
await app.RunAsync();

// ✅ C# 13: Primary constructor on record
public record AppSettings(
    string Environment,
    string ConnectionString,
    int MaxRetries,
    bool IsDebugMode);

// ✅ C# 13: Primary constructor on class
public class ConsoleApp(string[] args) 
{
    private readonly AppSettings _settings = LoadSettings();
    private readonly ILogger _logger = new ConsoleLogger();

    public async Task RunAsync()
    {
        _logger.LogInfo("Console app starting with {Count} arguments", args.Length);

        // ✅ C# 13: Params collections
        if (args.Length > 0 && args[0] == "--help")
        {
            ShowHelp();
            return;
        }

        // ✅ Main application logic
        await ProcessAsync();
        
        _logger.LogInfo("Console app completed");
    }

    private static AppSettings LoadSettings()
    {
        // ✅ C# 13: Field keyword in property
        return new AppSettings(
            Environment: Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development",
            ConnectionString: Environment.GetEnvironmentVariable("CONNECTION_STRING") ?? "Default",
            MaxRetries: int.TryParse(Environment.GetEnvironmentVariable("MAX_RETRIES"), out var retries) ? retries : 3,
            IsDebugMode: bool.TryParse(Environment.GetEnvironmentVariable("DEBUG_MODE"), out var debug) ? debug : false
        );
    }

    private async Task ProcessAsync()
    {
        _logger.LogInfo("Processing in {Environment} environment", _settings.Environment);
        
        // ✅ Simulate work with retry
        for (int i = 0; i < _settings.MaxRetries; i++)
        {
            try
            {
                await DoWorkAsync();
                break;
            }
            catch (Exception ex)
            {
                _logger.LogError("Attempt {Attempt} failed: {Error}", i + 1, ex.Message);
                
                if (i == _settings.MaxRetries - 1)
                {
                    _logger.LogError("All retries exhausted");
                    throw;
                }
                
                await Task.Delay(1000 * (i + 1));
            }
        }
    }

    private async Task DoWorkAsync()
    {
        // Simulate work
        await Task.Delay(1000);
        Console.WriteLine("Work completed successfully!");
    }

    private void ShowHelp()
    {
        // ✅ C# 13: Collection expressions
        string[] helpLines = [
            "Modern Console App Help",
            "=======================",
            "",
            "Usage: dotnet run [options]",
            "",
            "Options:",
            "  --help    Show this help message",
            ",
            "Environment Variables:",
            "  ASPNETCORE_ENVIRONMENT  Development | Staging | Production",
            "  CONNECTION_STRING       Database connection string",
            "  MAX_RETRIES             Maximum retry attempts (default: 3)",
            "  DEBUG_MODE              true | false (default: false)"
        ];
        
        foreach (var line in helpLines)
        {
            Console.WriteLine(line);
        }
    }
}

// ✅ Simple logger
public class ConsoleLogger : ILogger
{
    public void LogInfo(string message, params object[] args)
    {
        Console.WriteLine($"[INFO] {string.Format(message, args)}");
    }

    public void LogError(string message, params object[] args)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine($"[ERROR] {string.Format(message, args)}");
        Console.ResetColor();
    }
}

public interface ILogger
{
    void LogInfo(string message, params object[] args);
    void LogError(string message, params object[] args);
}

Related posts:

Pattern Matching for Cleaner Logic

Pattern Matching for Cleaner Logic

C# — string.Equals() Without ComparisonType Is a Bug

C# — string.Equals() Without ComparisonType Is a Bug

C#: Use Required Keyword to Enforce Property Initialization

C#: Use Required Keyword to Enforce Property Initialization

Views: 17
Found this useful? Share it
XLinkedInWhatsApp

Post navigation

SQL Execution Plan Reuse: Boost Query Performance with Plan Caching
Step-by-Step: Secure Configuration Management in Kubernetes with ConfigMap and Secrets

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Most Read

  1. 01How to make theater mode the default for Youtube 1,079 views
  2. 02How to add default value for Entity Framework migrations for DateTime and Bool 997 views
  3. 03Get the User Name and Domain Name from an Email Address in SQL 996 views
  4. 04Get the First and Last Word from a String or Sentence in SQL 873 views
  5. 05How to select distinct rows in a datatable in C# 868 views
  6. 06How to enable, disable and check if Service Broker is enabled on a database in SQL Server 671 views
  7. 07Add Constraint to SQL Table to ensure email contains @ 631 views
  8. 08Average of all values in a column that are not zero in SQL 584 views
  9. 09How to use Map Mode for Vertical Scroll Mode in Visual Studio 561 views
Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
Back to top
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com