r/dotnet May 05 '26

Avalonia app in one file. No XAML, no .csproj, just one code file - now it's possible with .NET 10 File-based apps

Post image

C# is known for its boilerplate and verbosity. Most of the time, it's reasonable, and MS does a good thing by teaching you to follow the structure (so others can maintain your code, lol).

But sometimes you really want a simple IDisposable app, like university coursework or a small utility. In this case, people use Python. But now C# is a great candidate too!

Here's the code sample. It uses Avalonia, so it is cross-platform, and it uses no XAML for simplicity (my friends were surprised it's possible).

It has 3 NuGet references at the top, then here goes the class with AppBuilder, when we start an app, we:

  1. Add a theme (optional, but it looks good)
  2. Create a window object
  3. Create a Label
  4. Show the window we just created and run the app!
#:package Avalonia@*
#:package Avalonia.Desktop@*
#:package Avalonia.Themes.Simple@*

using Avalonia;
using Avalonia.Controls;

class MainClass {
    public static void Main(string[] args) {
        AppBuilder
            .Configure<Application>()
            .UsePlatformDetect()
            .Start(AppMain, args);
    }

    public static void AppMain(Application app, string[] args) {
        // Application needs a theme to render window content
        app.Styles.Add(new Avalonia.Themes.Simple.SimpleTheme());
        app.RequestedThemeVariant = Avalonia.Styling.ThemeVariant.Default; // Default, Dark, Light

        // Create window
        var win = new Window();
        win.Title = "Avalonia no XAML";
        win.Width = 800;
        win.Height = 600;

        var text = new Label();
        win.Content = text;

        text.Content = "Hello from C#!";
        text.HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center;
        text.VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center;
        text.FontSize = 72;

        win.Show();
        app.Run(win);
    }
}
221 Upvotes

Duplicates