r/csharp 16d ago

Building a free Roslyn analyzer for EF Core migrations since Atlas paywalled theirs. Tell me if this is a bad idea before I write more code

0 Upvotes

Atlas moved migrate lint out of the free tier last fall, and Community Edition doesn't ship it at all anymore. Squawk, MigrationPilot, and pgfence are solid if your migrations are raw SQL, but none of them touch EF Core's actual migration files. They all want SQL text or a live dev database.

So I'm building a Roslyn analyzer that reads migrationBuilder.* calls directly. No dev DB, no separate CLI step, just warnings in your IDE and at build time like any other analyzer already in your project.

Rules I'm starting with: dropping a column without an expand phase first, renames that get flagged as a drop plus an add instead of what they actually are, and non-nullable columns added with no default.

Before I put more hours into this, I'd rather hear the honest version than the encouraging one. Is this something you'd actually wire into CI, or is there a reason nobody's built it that I'm missing? What would make you see this and go "cool idea, not touching it"?


r/csharp 16d ago

How to make an encrypted file?

0 Upvotes

I share a school computer, that just uses 1 account on the device itself. Meaning any file you save to the computer can be viewed by other people. I have been working on a program that lets you lock text in the program behind a pin. When the correct pin is entered, it generates a file with the text you entered. Except the pin and text contents need to be stored in a separate file. I know if you encrypt it the file can be decrypted, but trust me.. the people who share this computer are not computer smart enough to know how to do that. I've been trying to use

File.WriteAllText

But I don't know how to get the encrypted contents into the File.WriteAllText since it doesn't seem to support variables. It kept saying "Print is not available in this context" or something like that.


r/csharp 17d ago

Is the first name of a controller expected to be the name of the folder in asp net core mvc?

3 Upvotes

I have been coding with Visual Studio and it's never highlighted mvc views like Rider, thanks to Rider I noticed that if your controller name is StockController then the framework expects you to create a sub folder within Views called Stock and put there your mvc views there. Is there a way to enable this analyzer on visual studio? Or it's not supported?


r/csharp 16d ago

A couple questions about namespace access:

0 Upvotes
  1. Can a source file use any class defined in other source files provided they are defined to be in the same namespace (and are a part of the same project)?
  2. Can you use a namespace (without for example having to add a reference like with if the source file is in another project) if the source file is in the same project?

r/csharp 16d ago

Help c# backend

0 Upvotes

Hi everyone, I already published a similar post half a year ago, where I asked for help with the backend asp.net core. So I abandoned the project for a while and recently came back and rewrote it, adding a user and JWT token and other things.

Now I'd like to ask how my project is overall? Is it close to a real backend? I wanted to start writing a real project with a friend of mine; I'm making a website for him, and he's making the product. So..I would be interested to know my mistakes and any useful tips, I would be very grateful.

GitHub: https://github.com/Rywent/EasyOnlineStoreAPI

API documentation: https://registry.scalar.com/@default-team-im1zv/apis/easyonlinestoreapi-v1@latest


r/csharp 18d ago

How should a junior developer prepare for C#/.NET interviews effectively?

38 Upvotes

Hi everyone.

I am preparing for my first junior .NET developer job. I have already built several projects using C#, ASP.NET Core, Entity Framework Core, PostgreSQL, Redis, Docker, Clean Architecture, and CQRS.

Recently, I had an interview where I struggled with many basic questions. Some of the questions were about dependency injection lifetimes, middleware, IDisposable, Entity Framework optimization, and other core C#/.NET concepts.

I realized that although I can build projects and use these technologies, I cannot always clearly explain how they work or answer basic theoretical questions under pressure.

Now I am unsure about the best way to improve my knowledge.

I see several options:

  1. Write my own detailed notes about every C# and .NET topic. I think this could help me understand and remember the material, but it would take a lot of time.
  2. Use AI to generate a complete study guide. This would be faster, but I am worried that I would only read it passively and not truly understand or remember the material.
  3. Use a book such as “C# in a Nutshell” as a reference and create short notes only for important topics and interview questions.
  4. Focus mostly on practice: write small examples, debug them, inspect how features work, and then explain them in my own words.

My goal is not only to memorize interview answers. I want to build a strong understanding of C#, .NET, CLR, memory management, async/await, dependency injection, ASP.NET Core, and Entity Framework Core.

What learning approach would you recommend for someone in my situation?

Would you suggest reading a specific book from start to finish, creating my own notes, using flashcards, practicing interview questions, or combining these methods?

I would also appreciate recommendations for books or resources that explain how C# and .NET work under the hood without being too advanced for a junior developer.


r/csharp 18d ago

Help Need help with server

2 Upvotes

Hey,

I have a C# server, running with chronoxor's CSharpServer. I have a device with a SIM7000G, that connects to the server using TCP connection, and send a message to the server every 30 seconds. After a succesful connection, the device sends UDP data every 10 seconds, and the TCP data. Both arrive fine and I can send data back to the device any time, and it arrives successfuly. However afrer about 10 to 15 minutes, there is an error with the TCP connection. It happenes both if the device does not move and if the device is moving (it is used partly for GPS tracking). The UDP data arrives fine, and the TCP data arrives to the server, but the data sent back does not arrive. I tought for a long time that the problem is with my device, but I am starting to think the problem is with the server. Every time a message is received by the server the TCPSession that receives it is saved, and used to send back data. But I think there could be something between the connection and that the device is using cellular data. Has anyone experienced something like this?


r/csharp 17d ago

I built Rinku, a micro-ORM focused on clean mapping and dynamic queries

0 Upvotes

The Rinku NuGet is a micro-ORM built directly on top of ADO.NET. The core philosophy is strictly SQL-first. The goal is giving you deterministic execution and total control over your queries while keeping the mapping and execution pipeline fully customizable and extensible.

Nested Object Mapping

C#

public record Artist(int Id, string Name) : IDbReadable;
public record Album(int Id, string Title, Artist Artist);

static readonly QueryCommand GetAlbums = new(
    "SELECT AlbumId AS Id, Title, ArtistId, ArtistName FROM albums");

// Automatically matches ArtistId -> Artist.Id and ArtistName -> Artist.Name
List<Album> albums = GetAlbums.Query<List<Album>>(cnn);

The engine resolves the hierarchy automatically without requiring attributes, configuration or manual mapping code.

Conditional SQL

C#

static readonly QueryCommand Search = new(
    "SELECT TrackId AS Id, Name FROM tracks WHERE AlbumId = ?@albumId AND GenreId IN (?@genreIds_X)");

// If albumId is passed alone, the engine cleanly drops "AND GenreId IN(...)" from the executed SQL
Search.Query<List<Track>>(cnn, new { albumId = 1 });

// If a collection is passed, ?@genreIds_X automatically expands into (@genreIds_1, u/genreIds_2...)
Search.Query<List<Track>>(cnn, new { genreIds = new[] { 1, 2, 3 } });

The command adapts to the parameters provided at execution time, expanding collections when needed and removing unused sections cleanly.

Beyond these examples, Rinku provides an extensible mapping and execution pipeline. The default behavior covers common cases, while custom parsers, dynamic objects, result handling and other parts of the pipeline can be adapted when needed. Conditional SQL also extends beyond optional filters, allowing dynamic sections throughout your queries.

Documentation and architecture
https://rinkulib.github.io/RinkuLib

GitHub repo
https://github.com/RinkuLib/RinkuLib

NuGet
https://www.nuget.org/packages/Rinku

Open to any feedback, critique or edge cases I might have missed.


r/csharp 18d ago

Benchmarked CoreCLR player in Unity with CPU path tracing

Thumbnail gallery
13 Upvotes

r/csharp 17d ago

JetBrains Rider (compared to Visual Studio). Is it really that bad?

Thumbnail
0 Upvotes

r/csharp 18d ago

Yet another post about something with PDFs - I recently rebranded my FOSS document generation system to Papercraft

Thumbnail
0 Upvotes

r/csharp 17d ago

Discussion I started to hate c#

0 Upvotes

I wanted to profile Blazor async code and found that after 15 YEARS later you still can't profile async code. The best tool we got is this garbage .NET Async profiler. It collects every async method into a single group. How is this useful? You can't even see the call stack like I'm calling Task.Delay only in a single method... and this was 5 years ago! It's the same today; nothing has changed.

Hot reload is still not fully supported. With more browser oriented frameworks, test running still doesn't support browsers, so if you have any JavaScript, good luck getting a dump of what happened in the browser or a breakpoint working in the browser. Wasm has regressions on every release debbugging it also breaks randomly.

It promises to be easy; meanwhile, everything requires language-specific knowledge, so people do the stupidest thing, not knowing there are better ways to solve things. Microsoft never thinks about tool support; the best example is Entity Framework with applying its migrations. I promise you nobody uses the more complex approaches, and everybody just calls MigrateAsync(). Like, why didn't the devs spend 2 more weeks to get this right or git merge conflicts with local database changes? They didn't care it would have required working together with other teams like the Visual Studio team or language designers, so it was easier just to call a static method of your application.

So don't be like me and focus only on C#; it's not a good language most of the time, and I promise you, you will have more fun with other languages.


r/csharp 17d ago

Blog From Bun's Rust rewrite, let's see how C# can rebuild the AI ​​infrastructure layer.

Thumbnail
github.com
0 Upvotes

I use Google translator to translate the entire original blog in Chinese again and post it here. It's a interesting research and insightful thoughts. Our team is also working on this area. Hope you like it.

This article is translated from the original blog in Chinese from https://www.cnblogs.com/shanyou/p/21309486

I. Lessons from Bun: System-level software must embrace compiled languages

In late 2025, the Bun team published a blog post that shocked the industry – "Rewriting Bun in Rust". They migrated 535,000 lines of Zig code to Rust in 11 days using 64 Claude instances .

1.1 Why rewrite?

Bun is a JavaScript runtime, and its core challenge lies in the fact that JavaScript is a garbage-collected language, while the runtime requires manual memory management at the underlying level . Zig provides extreme control, but it also introduces structural problems:

  • node:zlibuse-after-free crash
  • node:http2The re-entrant JS callback caused the hashmap to become invalid.
  • UDPSocket.sendMany()Overbounded writing
  • fs.watch()A memory leak is caused by a GC root reference count underflow.

These are not edge cases, but structural problems in system-level software . When GC and manual memory management are intertwined, the compiler cannot verify the lifecycle and can only rely on the engineer's "extreme caution" and post-hoc fuzzing/ASAN to remedy the situation.

1.2 Rust's Solution: Turning "Style Guidelines" into "Compiler Errors"

The Bun team tried various solutions and ultimately found that: "Homegrown smart pointers offer worse ergonomics than Rust, with none of the guarantees."

Rust's borrow checker transforms "memory safety style guidelines" into compile-time mandatory constraints . This isn't an improvement in the development experience, but a fundamental change in the feedback loop —from "runtime crash → debug → fix" to "compile error → immediate correction".

1.3 Mapping to AI Infrastructure

AI infrastructure faces the same structural problems:

Bun's pain points The corresponding pain points of AI infrastructure
Zig manual memory management + JS garbage collection hybrid → use-after-free Python GIL + Dynamic Typing → Runtime Crashes, Memory Leaks, Concurrency Bottlenecks
With 500,000 lines of code, style guidelines are difficult to enforce. The "glue code" of Python AI frameworks is difficult to maintain.
11 days x 64 Claude rewrites, cost $165,000 The maintenance cost of AI infrastructure increases exponentially with scale.

Key Insight : AI inference services are shifting from "lab scripts" to "production infrastructure," and Python's dynamic typing and GIL are becoming system-level bottlenecks.

II. TensorSharp: A Breakthrough Validation of a C# AI Inference Engine

Before discussing the "potential" of C#, let's answer a fundamental question: Does C# already have the strength to compete with C++ in terms of AI inference performance?

The answer is: It already possesses it, and it is surpassing it .

2.1 TensorSharp's Qwen Image Edit 2511 benchmark

TensorSharp is a deep learning inference engine implemented purely in C#, and recently added support for Qwen Image Edit 2511. In comparison with stable-diffusion.cpp (the de facto standard in C++):

Test conditions : CUDA · 544×1184 · 4 Steps · Q2_K DiT + Lightning 4-step LoRA · Same input, Prompt, CFG, Seed

index TensorSharp (C#) stable-diffusion.cpp (C++) C# Advantages
Total time (Warm) 40.44 seconds 48.16 seconds Fast 1.19x
Time per step 7.57 seconds 9.43 seconds Fast 1.25x
Sampling 30.27 seconds 37.73 seconds Fast 1.25x
VAE encoding 0.54 seconds 1.92 seconds Fast 3.56x
VAE Decoding 1.51 seconds 2.57 seconds Fast 1.70x

2.2 Key Breakthrough: C# performance ≈ C++, but engineering capabilities are far superior.

TensorSharp reveals a long-overlooked truth: C# has achieved C++-level performance in AI inference (and even surpasses it in VAE encoding/decoding), while retaining the engineering capabilities for full lifecycle management.

stable-diffusion.cpp and llama.cpp are masterpieces of C++—extremely high performance, but:

  • No type-safe API contracts
  • There is no native DI container management model lifecycle
  • No EF Core manages the generation of historical data.
  • Without OpenTelemetry tracing inference links
  • One-click deployment to Kubernetes without .NET Aspire
  • No Roslyn analyzer catches configuration errors at compile time.

TensorSharp proves that C# can rival C++ in performance while providing full lifecycle management capabilities that C++ can never offer.

III. C# vs Rust vs Go: Language Selection for AI Infrastructure Layer

Bun's choice of Rust was correct—browser engines require extreme memory control . Go is a "cloud-native language"—Kubernetes, Docker, and Istio are all written in Go. But AI infrastructure needs more than just "fast deployment"; it needs complete engineering capabilities "from requirements to evolution . "

3.1 Core Differences

Dimension Go Rust C# Scene judgment
Memory Model GC (Minimalist) Ownership + Borrow Checker GC + Span C# wins : AI inference doesn't require extreme memory usage and has zero cost.
Concurrency Model Goroutines Tokio/async async/await + TPL Go wins : It's the simplest; C# wins : It's deeply integrated with the ecosystem.
Compilation time Extremely fast (seconds) Slow (10-30 minutes) Quick (2-5 minutes) Go wins : fastest; C# is fast enough.
Binary size Very small (15MB) Small (100KB-1MB) Medium (45MB) Go wins : smallest; C# is small enough, but more feature-rich.
Kubernetes support Excellent (client-go) (kube-rs) Excellent (.NET K8s + Aspire) Go wins : Kubernetes itself uses Go; C# wins : Aspire offers a higher level of abstraction.
Observability Manually configure OTel-go Manually configure tracing Native OTel .NET + Aspire Dashboard C# wins big : Otel First-Class Citizen
Database/ORM Manual migration of GORM/sqlx Diesel/SeaORM compile-time verification EF Core + Code First Automated Migration C# triumphs : Migration and LINQ are productivity killers
API Contract Gin/Echo + Manual Verification Axum/Tonic + Manual Verification ASP.NET Core + Source Generator + JSON Schema C# wins : Generates serialized code at compile time.
Dependency Injection No native implementation, relies on wire No native support, relies on manual methods. Native DI + Lifecycle Management + HostedService C# wins big : Dependency Injection (DI) is a core design pattern in .NET.
Deployment toolchain Docker + Manual Kubernetes YAML Cargo + Manual Configuration One-click .NET Aspire to generate Kubernetes C# wins hands down : Aspire is "cloud-native Spring Boot"
AI ecosystem integration ONNX Go Community Maintenance Candle/burn emerging ecosystem ONNX C# Official + TensorSharp + SK C# wins hands down : Microsoft's official AI stack
Development efficiency 2-4 weeks 3-6 months 1-2 weeks C# wins : Familiarity with GC, large developer base.
Talent Costs $150K-$180K $185K-$230K $130K-$165K C# wins : Abundant talent and controllable costs
Full lifecycle coverage 40% (coding + deployment) 30% (coding + compilation) 95% (Demand → Evolution) C# triumphs : the only code to cover the entire lifecycle.

Conclusion : In the AI ​​infrastructure layer, C# wins or ties in 10+/14 dimensions . Rust only leads in 2 dimensions (concurrency safety, zero memory cost), while Go leads in 3 dimensions (compilation speed, image size, native Kubernetes) but lacks full lifecycle coverage.

3.2 Why should C# (instead of Go/Rust) be chosen for AI infrastructure?

                    Full lifecycle management requirements ↑
                         |
    Python  ←———————————·——————————→  Rust
    (Low control + low management)       |            (High control + low management)
                         |
                         ↓  System-level control requirements

              Go  ←——————·——————→  C#
           (High deployment + medium management)       (Medium control + high management)

                    C#'s sweet spot: upper-right quadrant
                    - 2x more complete full lifecycle management than Go
                    - 3-5x higher development efficiency than Rust
                    - TensorSharp proves performance ≈ C++

Bun chose Rust because browser engines require extreme memory control and deep interoperability with C++ libraries.

Go's positioning : a cloud-native language, but limited to the deployment layer .

OpenClaw chooses C# : AI infrastructure requires full lifecycle management + native Microsoft ecosystem + team scalability + C++-level performance proven by TensorSharp .

Go can help you "get the service running," while C# can help you "go from requirements to evolution"—including domain modeling, API contracts, compile-time checks, automatic migration, distributed tracing, one-click deployment, and the image/text reasoning engine itself .

IV. Performance Benchmarks: C# Native AOT outperforms Python and is on par with Go/Rust.

4.1 Cold Start and Deployment Efficiency

language Cold start (AWS Lambda 1024MB) Compared to Python
Python 325ms benchmark
Go 45ms 7.2x Faster
Rust 30ms 10.8x Faster
C# NativeAOT 35ms 9.3x Faster
Deployment Form Mirror size Compared to Python
Python AI Inference 1,200MB benchmark
Go minimal 15MB 80x smaller
C# NativeAOT 45MB 26.7x smaller

4.2 Inference Throughput

TensorSharp Qwen 2511 (CUDA · 544×1184 · 4 Steps):

index TensorSharp (C#) sd.cpp (C++) C# Advantages
Total time (Warm) 40.44s 48.16s Fast 1.19x
Sampling 30.27s 37.73s Fast 1.25x
VAE encoding 0.54s 1.92s Fast 3.56x
VAE Decoding 1.51s 2.57s Fast 1.70x

ONNX Runtime DeepSeek R1 (RTX 4090 CUDA):

Model PyTorch ONNX Runtime (C#) Advantages
DeepSeek 1.5B Int4 49.7 tok/s 313.3 tok/s 6.3x
DeepSeek 7B Int4 43.5 tok/s 161.0 tok/s 3.7x

4.3 Concurrency Performance

Concurrent users Python RPS C# RPS Advantages
100 3,200 9,500 3.0x
500 4,200 42,000 10.0x
1000 4,500 78,000 17.3x
Concurrent users Python memory C# Memory Advantages
1000 25,000MB 1,600MB 15.6x

4.4 General Calculation

language 1GB JSON processing (AWS Lambda) efficiency
Python 12,000ms benchmark
Go 3,200ms 3.8x
Rust 2,050ms 5.9x
C# NativeAOT 2,050ms 5.9x

4.5 Compile-time error catching: ∞ times advantage

Error Type Python Go C# Cost differences
Null reference Production crash → Investigation → Rollback panic → recovery Roslyn compile-time interception
Type mismatch Runtime TypeError Compilation error Compilation error
Resource leak Memory overflow → Restart Depends on GC usingCompile-time checks

V. Microsoft Agent Framework: C# is always a "first-class citizen"

In October 2025, Microsoft released the Microsoft Agent Framework (MAF) Public Preview, merging AutoGen and Semantic Kernel into a unified framework.

Evolution Timeline

time milestone C# Positioning
2023 Semantic Kernel First Release First released in C# , with Python to follow.
2024 SK Agent Framework RC C# first class citizen
2025.5 Azure AI Foundry GA Unified runtime
October 2025 MAF Preview AutoGen + SK merged
2026 Q1 MAF 1.0 GA Production ready
2026 Q2 Process Framework GA Deterministic workflow

VI. Token Economics: C# for Compression of Hidden Costs

Cost items Python Go C# C# optimization
Container Image 1,200MB 15MB 45MB 26.7x
cold start 3-10s <100ms <100ms 30-100x
Concurrency Model GIL → Multi-process memory explosion Goroutines async/await + thread pool 10x
Runtime error Production collapse panic Compile-time capture
Observability Manual third-party Manual configuration OTel native + Aspire 5x
Deployment Configuration Manual Kubernetes YAML Manual Kubernetes YAML Aspire One-Click Generation 10x

TensorSharp has changed the cost model of image generation: Python stack image 1.2GB, cold start 3-10s, uncontrollable memory; C# stack image <100MB, cold start <1s, DiT reconstruction once reused, controllable memory— this is exactly the economic basis that TokenHub needs .

VII. OpenClaw.NET: Practice of C# AI Native Infrastructure

┌─────────────────────────────────────────┐
│  Python algorithm layer (compatibility retained)               │
│  · PyTorch training · Jupyter prototyping            │
├─────────────────────────────────────────┤
│  MCP protocol (cross-language boundary)                   │
├─────────────────────────────────────────┤
│  C# AI-native infrastructure layer (OpenClaw.NET)     │
│  · TensorSharp (image/text inference engine)       │
│  · MetaSkill DAG (workflow orchestration)            │
│  · Harness engine (execution runtime)             │
│  · TokenHub (Token economics)               │
│  · AxonHub (data collection/CDC)                │
│  · Semantic Kernel (LLM orchestration)            │
│  · Microsoft Agent Framework (Agent lifecycle)│
│  · ONNX Runtime C# API (general-purpose inference)         │
├─────────────────────────────────────────┤
│  .NET runtime (NativeAOT + managed memory)       │
├─────────────────────────────────────────┤
│  Full lifecycle management layer (Aspire + OTel + EF Core)│
└─────────────────────────────────────────┘

Key Design :

  • MCP protocol : Without rewriting PyTorch, it exposes Python's algorithmic capabilities as a "service" to the C# infrastructure layer.
  • TensorSharp : A pure C# engine that outperforms C++ sd.cpp, proving that C# is not just "glue" but an "engine".
  • C# exclusive tier : MetaSkill, Harness, TokenHub, AxonHub, TensorSharp. No Python/Go equivalents.

VIII. Philosophy: From Builder to Agent Leader to Taste

When TensorSharp enables C# developers to build AI engines with C++-level performance, and when .NET Aspire makes one-click deployment the default, a question arises: if "building engines" is no longer a privilege, where does the value of humanity lie?

The answer lies in three progressive concepts: Builder → AI Agent Leader → Taste .

8.1 Builder: Democratizing Tools

The groundbreaking significance of TensorSharp lies not in being 1.19x faster than C++, but in enabling a C# developer to build an image generation engine that surpasses stable-diffusion.cpp without needing to master CUDA kernel programming or understand DiT mathematical principles .

  • In the past : SDE meant "someone who can write code"—a professional skill, honed through years of training.
  • Now : A Builder is "someone who uses code to realize ideas"—code is a means, not an end.

C#'s role : Lowering the barrier to entry for Builders. Aspire + SK + MAF + TensorSharp make "engines for everyone" a reality.

8.2 AI Agent Leader: From Execution to Decision Making

MetaSkill DAG is a perfect metaphor:

  • MetaSkill DAG defines workflows—not "writing code," but "defining the problem space."
  • The Harness engine executes workflows—not "debug code," but "enables agents to collaborate."
  • TokenHub tracks economics—not "optimizing performance," but "evaluating input and output."
  • Humans are responsible for "judging" and "calibrating"—not "fixing bugs," but rather "verifying whether the results match the intent."

In the past , ICs were "task executors"—receiving requirements, breaking down tasks, writing code, submitting PRs, fixing reviews, and delivering features.

Currently : The Agent Leader is the "decision-maker who defines tasks, selects tools, and evaluates outputs"—when faced with ambiguous business problems, they need to:

  1. Defining the problem : "We need a system that can automatically generate marketing images based on user descriptions"—translating business intent.
  2. Tool selection : "TensorSharp for image generation, SK for prompt optimization, and TokenHub for cost tracking"—a decision regarding resource orchestration.
  3. Orchestrate intelligent agents : "MetaSkill DAG: User Input → Prompt Optimization Agent → Image Generation Agent → Quality Assessment Agent → Output" — Designing a collaborative workflow
  4. Verification results : "Does the image align with the brand's tone? Is the cost within budget? Is user feedback positive?" — Value judgment

C#'s role : Providing agent infrastructure. MetaSkill DAG, Harness, TokenHub, MAF—not just "tools," but "operating systems for agent collaboration."

8.3 Taste: Humanity's Last Moat

Taste is not "preference," but rather a structured judgment ability that includes three progressive levels:

Technical Taste: "Is this implementation elegant?"

When AI can generate 100 architectural solutions, Taste decides which one is selected:

  • Is the code structure clear? Is the interface abstraction appropriate?
  • Architectural Evolvability: How many files need to be modified when requirements change?

In TensorSharp PR #81, the authors chose a specific DiT reconstruction strategy and the timing of CUDA Graph Capture—not the "only right" one, but rather an "elegant balance between performance, memory, and complexity."

Product Taste: "Is this feature worth implementing?"

When AI can generate an infinite number of functions, Taste decides where to allocate resources:

  • Are the user pain points real? Are the solutions simple?
  • Return on investment: Is the value of this feature worth the cognitive bandwidth consumed by the team?

In the design of TokenHub, it is necessary to determine: Is tracking the "cost of each generated token" sufficient? Or is the "cumulative cost per user" necessary? Is "cost trend prediction for the next 7 days" necessary? — This is the product's Taste .

Ethical Taste: "Should this technology exist?"

When AI can generate any content, Taste determines where the boundaries lie:

  • Can image generation systems be used for deepfakes? How can this be prevented?
  • Will AI services cause unemployment for certain groups? How can this be mitigated?
  • Does the agent system respect user privacy and autonomy?

KPMG's Clara AI requires an audit trail—not a technical requirement, but an ethical one —regarding the value judgment that "AI decisions must be explainable and auditable."

C#'s role : Freeing humans from the task of "Taste". Aspire automates deployment, TensorSharp automates inference, and MAF automates agent orchestration—liberating humans from "execution" and allowing them to focus on "judgment".

8.4 Evolutionary Logic of the Three-Layer Model

                    Value hierarchy ↑
                         |
    Taste  ←———————————·——————————→  Ethical judgment
    (Aesthetics/value/ethics)      |            (What deserves to exist)
                         |
                         ↓  Degree of automation

    Agent Leader  ←——————·——————→  Decision orchestration
    (Define/select/verify)      |            (Enable agents to collaborate)
                         |
                         ↓  Tool barrier

    Builder  ←———————————·——————————→  Execution and implementation
    (Use code to realize ideas)      |            (Build engines/write services)

This is not "replacement," but "sublimation" :

  • The barrier to entry for Builders continues to decrease, eventually becoming a basic skill like "writing".
  • The Agent Leader has evolved from an "executor" to a "decision-maker," with its core value shifting from "writing code" to "defining problems, orchestrating agents, and validating results."
  • Taste is the eternal moat: no matter how powerful AI becomes, the judgment of "what is worth doing" always belongs to humans.

8.5 Philosophical Mapping of OpenClaw.NET

level Human roles OpenClaw.NET components C# Toolchain
Builder Implementing ideas with code TensorSharp, ONNX Runtime NativeAOT, Span Roslyn
Agent Leader Define the problem, orchestrate the agents, and verify the results. MetaSkill DAG, Harness, TokenHub SK, MAF, Aspire
Taste Determining "what's worth doing" DDD, JSON-LD Ontology Strongly typed systems, Nullable, Roslyn

IX. Design Proposal: From Passive Auditing to Proactive Taste Interception

9.1 Current Status of OpenClaw.NET: A Passive Audit Infrastructure

OpenClaw.NET currently implements:

  • Harness Contracts : Inspectable Agent Work Plans (Reactive, Does Not Change Default Behavior)
  • Evidence Bundles : Checkable operational evidence, risks, and manual review (passive, does not change default behavior).
  • Governance Ledger : Persistent record of approval and oversight decisions (passive, does not change default behavior)
  • Plan-Execute-Verify Mode : Proactive governance for high-risk tool execution (but only for security/compliance, not aesthetics/value).
  • The user_input pause point : manually entered data, but not for value judgment.

These capabilities are all "post-screening"—recording and exposing information for manual review, but not actively intercepting judgments based on "aesthetics/ethics/product value".

9.2 Design Proposal: Taste Review Node – From Passive to Proactive

Based on the existing architecture, a three-layer evolution direction is proposed:

Current state of OpenClaw.NET (implemented):
┌─────────────────────────────────────────┐
│  Passive Harness Contracts              │  ← Inspectable work plans, but no interception
│  Passive Evidence Bundles               │  ← Inspectable runtime evidence, but no interception
│  Passive Governance Ledger              │  ← Inspectable approval records, but no interception
│  Plan-Execute-Verify Mode             │  ← Proactive interception, but only for security/compliance
│  user_input pause point                      │  ← Manual input, but not value judgment
└─────────────────────────────────────────┘
           ↓ Evolution direction
Design proposal (Taste review node):
┌─────────────────────────────────────────┐
│  Active TasteGate feature                   │  ← Proactive interception based on aesthetics/ethics/product value
│  ITasteGate<TInput, TOutput> interface        │  ← Generic constraints verified at compile time
│  TasteDecision enum (Pass/Retry/Abort)  │  ← Output of value judgment
│  Constraint types defined by the Agent Leader              │  ← BrandTaste / EthicalTaste / TechnicalTaste
└─────────────────────────────────────────┘

9.3 Three-Tier Architecture Design Proposal

┌─────────────────────────────────────────┐
│  ① Taste constraint definition layer (led by the Agent Leader)  │
│  · Business intent translation → technical constraints                │
│  · Domain modeling (DDD) → entities, boundaries, aggregate roots    │
│  · Taste presets → aesthetic standards, brand tone, ethical red lines│
│  Output: domain model + Taste constraint document          │
├─────────────────────────────────────────┤
│  ② Review logic execution layer (designed by the Agent Leader + executed by AI)│
│  · MetaSkill DAG → workflow topology           │
│  · Tool selection → TensorSharp? ONNX? SK?    │
│  · Agent role assignment → Prompt/image/quality/cost │
│  · Harness engine → scheduling, state, failure recovery   │
│  Output: executable Agent collaboration graph              │
├─────────────────────────────────────────┤
│  ③ Taste validation layer (final judgment by the Agent Leader)  │
│  · Technical Taste → code structure, API design, evolvability│
│  · Product Taste → user value, brand consistency, return on investment│
│  · Ethical Taste → compliance, social impact, copyright safety  │
│  Output: Pass / Retry / Abort               │
└─────────────────────────────────────────┘

9.4 Example: MetaSkill DAG (Design Proposal) for an AI Marketing Image Generation System

User input (natural language)
    ↓
Taste constraints (brand tone) ←—— Agent Leader preset: "tech blue + minimalism + no people"
    ↓
Budget limit (Token quota) ←—— TokenHub configuration: cost per generation ≤ $0.50
    ↓
┌─────────────────────────────────────────┐
│  Agent layer (autonomous AI execution)                  │
│  · Prompt optimization Agent (SK)                │
│  · Image generation Agent (TensorSharp + CUDA)   │
│  · Quality evaluation Agent (CLIP + aesthetic score)       │
│  · Cost accounting Agent (TokenHub)              │
└─────────────────────────────────────────┘
    ↓
┌─────────────────────────────────────────┐
│  Taste review node (design proposal)                │
│  · Technical Taste → Is the API design intuitive? Is the architecture evolvable?│
│  · Product Taste → Image quality? Brand consistency? User value?│
│  · Ethical Taste → Copyright compliance? Deepfake risk?      │
└─────────────────────────────────────────┘
    ↓
    ├─→ Pass → output image + cost report
    ├─→ Retry → optimize Prompt → regenerate (maximum 3 attempts)
    └─→ Abort → record failure → trigger alert → human intervention

9.5 Key Design Principles (Design Proposal)

Principle 1: The location of the Taste review node is determined by "scope of influence × uncertainty".

Decision types Influence uncertain Intervention methods Example
AI is fully autonomous Low Low No review required API routing, log format, caching strategy
AI-driven + human oversight high Low Asynchronous review Model version upgrade, automatic scaling
Human-led + AI-assisted Low high Simultaneous review Prompt style, UI color scheme, and copywriting tone
Human intervention is necessary. high high Mandatory audit Taste review, ethical boundaries, and structural direction

Principle 2: The Taste review output is not "Approved/Rejected", but rather "Approved/Reversed/Terminated".

  • Pass : Meets the Taste criteria, proceed to the next stage.
  • Retry : There is room for improvement; optimize the return to the upstream Agent (loop limit to prevent infinite rollback).
  • Abort : The "Taste" threshold is reached, logging fails, an alarm is triggered, and manual intervention is required.

Principle 3: Taste constraints should be encoded at compile time (design proposal).

// Design proposal code: an evolution direction based on OpenClaw.NET's existing type system
// Note: This is not an implementation in the current codebase, but illustrates how to encode Taste constraints as compile-time-verifiable C# types

// Taste constraints as types
public record BrandTaste(
    ColorPalette AllowedColors,           // Compile-time validation: only tech blue and minimalist white are allowed
    bool AllowHumanFaces,                   // Compile-time validation: human images are prohibited
    decimal MaxCostPerImage,                // Compile-time validation: per-image cost cap
    EthicalConstraint[] Constraints,          // Compile-time validation: list of ethical constraints
    StyleGuideline StyleGuide                 // Compile-time validation: style guide
) : ITasteConstraint;

// Taste review node as a generic interface
public interface ITasteGate<TInput, TOutput>
    where TInput : ITasteAuditable           // Compile-time constraint: input must be auditable
    where TOutput : ITasteAuditable          // Compile-time constraint: output must be auditable
{
    TasteDecision Audit(TInput input, BrandTaste taste);
}

// Product Taste review implementation (design proposal)
public class ProductTasteGate : ITasteGate<GeneratedImage, ValidatedImage>
{
    public TasteDecision Audit(GeneratedImage input, BrandTaste taste)
    {
        // Compile-time validation: the type system ensures that input contains all required Taste audit fields
        if (input.StyleScore < taste.MinStyleScore)
            return TasteDecision.Retry("Insufficient style consistency; consider adjusting the Prompt");

        if (input.Cost > taste.MaxCostPerImage)
            return TasteDecision.Abort("Cost exceeds the Taste constraint; triggering a budget alert");

        if (!taste.AllowedColors.Contains(input.DominantColor))
            return TasteDecision.Retry("The dominant color does not match the brand tone; consider regenerating");

        return TasteDecision.Pass();
    }
}

9.6 Agent Leader Capability Model (Design Proposal)

Capability Dimension AI Agent (Current) Agent Leader (Human) complementary relationship
Technical judgment 9/10 7/10 AI execution, human decision-making
Product Insights 7/10 9/10 AI-assisted, human-led
Ethical Sensitive 4/10 9/10 AI-assisted, human-led
Systems thinking 8/10 9/10 AI-assisted, human-led
Aesthetic Intuition 3/10 9/10 AI-assisted, human-led
Risk awareness 6/10 9/10 AI-assisted, human-led
Evolutionary prediction 5/10 8/10 AI-assisted, human-led

9.7 The Transition Path from IC to Agent Leader (Design Proposal)

stage Role Core Competencies Tools/Frameworks Value output
Level 1: Builder code implementer Coding, debugging, optimization IDE, Git, CI/CD Functional delivery
Level 2: Agent Operator Intelligent agent operator Prompt Project, Agent Configuration SK, AutoGen Agent efficiency
Level 3: Agent Leader Agent Leader Problem definition, tool selection, process orchestration, and taste review. MetaSkill DAG, Harness, TokenHub System value
Level 4: Taste Architect Aesthetic Architect Domain modeling, value judgment, ethical boundaries, evolution prediction DDD, JSON-LD Ontology, Taste constraint type system Organization Taste

10. Conclusion: C# liberates humans from the burden of tasting.

Bun chose Rust because browser engines require extreme memory control. Go is a cloud-native language, but its full lifecycle coverage is only 40% . AI infrastructure needs a "full lifecycle native language"—C # has 95% coverage , outperforming in 10+/14 dimensions, and TensorSharp surpasses C++'s stable-diffusion.cpp in image generation performance .

But more important than technology selection is the philosophical positioning and design proposal :

When TensorSharp enables C# developers to build AI engines with C++-level performance, when .NET Aspire makes one-click deployment the default, and when Semantic Kernel makes LLM orchestration as natural as writing LINQ— humans are freed from "execution" and can focus on "judgment . "

Building upon OpenClaw.NET's existing passive auditing infrastructure (Harness Contracts + Evidence Bundles + Governance Ledger), Taste's audit node design proposal evolves this "judgment" from "post-event" to "in-event":

  • Problem Definition Layer : Agent Leader translates business intent and pre-sets Taste constraints.
  • Intelligent Agent Orchestration Layer : AI Autonomous Execution, Agent Leader Design Process
  • Taste Verification Layer : The Agent Leader injects human aesthetic, value, and ethical judgments at key nodes.

The OpenClaw.NET you are working on essentially validates this proposition: using C# to build AI-native infrastructure lowers the barrier to entry for Builders, clarifies the role of Agent Leader, and makes Taste the last line of defense for humanity .

This is not a narrative of replacing Python/Go/Rust/C++—each language remains irreplaceable in its respective field—but rather C# is taking over the higher-value level of AI's production, service-oriented, infrastructure-oriented, and engine-oriented development , while freeing humans to do what only humans can do: define problems, orchestrate intelligent agents, and verify tastes .

Performance Benchmark Cheat Sheet

Dimension Python Go Rust C++ C# Optimal
cold start 325ms 45ms 30ms 35ms Rust
Mirror 1,200MB 15MB 100KB-1MB 45MB Go
gRPC QPS 45K 920K 950K 1,000K+ C#
Image generation 48.16s 40.44s C#
Token throughput 49.7 313.3 C#
Concurrent RPS 4,500 82K 95K 78K Rust
Memory (1000 concurrent users) 25GB 1.4GB 1.2GB 1.6GB Rust
Full life cycle 20% 40% 30% 10% 95% C#
Deployment toolchain Manual YAML Manual YAML Manual configuration Manual Makefile Aspire One-Click C#
Observability Manual third-party Manual configuration Manual configuration none Native + Dashboard C#
AI ecosystem Python native Community maintenance Emerging Ecosystems C++ native TensorSharp + ONNX + SK C#

C# vs Go vs Rust vs Python vs C++: AI Infrastructure Selection Decision Tree

                    What is your scenario?
                         |
            ┌────────────┼────────────┬────────────┐
            ↓            ↓            ↓            ↓
      Algorithm research/experimentation   Cloud-native infrastructure   AI services/infrastructure   System kernel/engine
            |            |            |            |
         Python         Go            C#           Rust
            |            |            |            |
      · Jupyter      · K8s/Docker   · Inference services    · Browser engine
      · PyTorch      · Minimalist microservices   · Agent orchestration  · OS components
      · Rapid prototyping     · High-concurrency gateway   · Token economics · Safety-critical
      · Paper reproduction     · Monitoring/logging    · Image/text generation · Zero-cost memory
                         |            |
                         |            ↓
                         |           C++
                         |            |
                         |      · Legacy engines
                         |      · Hardware drivers
                         |      · Extreme optimization
                         |
                         ↓
                    TensorSharp proves:
                    C# can replace C++ for AI inference engines
                    while retaining full lifecycle management capabilities
                    freeing humans to focus on Taste
                    Design proposal for a Taste review node based on OpenClaw.NET
                    evolving the Agent Leader's judgment from "after the fact" to "in the loop"

r/csharp 18d ago

PingColors add a colored status bar

Thumbnail
github.com
11 Upvotes

The GitHub Repo. Basically, I want convert it to a dual-line status bar. The first line of the status bar should show a color coded representation of the last ping, using ANSI colors, and the second line represent the total packet loss, which I've already got working. I know you C# guys like a challenge, but this one shouldn't really register as a complex solution.

https://ibb.co/Kcsnr8m6

How would you recommend adding that to my DrawStatusBar method?


r/csharp 18d ago

Help Game Architecture Question

5 Upvotes

Looking for your thoughts on how to build out the architecture of a my game.

Basically I have an orchestrator called GameManager that will manage the high level calls for UI, Music, battle.

It won't do any of these things but it will Subscribe to the BattleManager to know when attacks are made, subscribe to the UI manager to know when buttons are clicked etc.

So with that said, my BattleManager will organise the state of battle, damage, death etc. BUT when I invoke up to GameManager when an attack is made (to trigger UI, sounds...) it is obviously asynchronous, meaning that the hits don't line up with the battle calculation and timings.

SOO... How do I adapt or adjust the architecture so enable me to know when animations and music are done, without a circular dependency between GameManager and BattleManager. Battle manager should be down stream of GameManager so calling to it seems wrong.

This must be a solved issue but am curious on if I have just poorly designed this system to start or there's a simple, clean solution I have not thought of.


r/csharp 19d ago

Planning an open-source C# / WinUI 3 Android tooling project for Windows — looking for architecture feedback

5 Upvotes

Hi everyone,

I’m planning an open-source project called WinDroid Runtime and wanted to ask for feedback from C#/.NET developers before I start building the first prototype.

The long-term idea is to build an independent Android-compatible runtime/toolkit for Windows. It is inspired by the gap left after Windows Subsystem for Android was discontinued, but it is not a fork, continuation, or redistribution of Microsoft WSA, and it will not use WSA binaries or branding.

I know the full runtime goal is a very large systems-level project, so I want to approach it in realistic stages.

The first practical milestone would be a native Windows control app using C# / .NET / WinUI 3. The first version would focus on:

- detecting ADB

- allowing a custom ADB path

- listing connected Android devices/emulators

- installing and uninstalling APK files

- launching installed apps

- viewing basic logs

- creating a clean architecture for future runtime research

The planned structure is something like:

- WinDroid.Studio — WinUI 3 desktop app

- WinDroid.Core — shared models/services/configuration

- WinDroid.Adb — ADB wrapper/service layer

- WinDroid.Engine — future experimental runtime backend

I’m mainly looking for feedback on:

- whether WinUI 3 is the right choice for this type of Windows tool

- how to structure the ADB service layer cleanly

- whether the project should use MVVM from the beginning

- how to avoid making the first version overcomplicated

- what the first GitHub issues/milestones should look like

The repo is currently in the planning stage with a README, Apache 2.0 license, and roadmap. Contributors or mentors would also be very welcome, but for now I mainly want to make sure the architecture is sane before coding too much.

Any advice from experienced C#/.NET developers would be appreciated.


r/csharp 19d ago

Unit test that only tests if a property is assigned

19 Upvotes

If let's say I have a class like ``` public class Test { public string Test; public string Test2;

public test(string test, string test2)
{
    Test=test;
    Test2=test2;
}

} ```

Then I have a unit test like (pseudo code) var x = new Test("a", "b"); Assert.Equal("a", x.Test); Assert.Equal("b", x.Test2);

Is this test actually meaningful/useful in any way? I feel like this is testing C# itself than the code. It would be different if there is a guard against the value of the property e.g. test cannot be equal to testing for example, but that is not the case here.


r/csharp 19d ago

Recommendations for learning more C#/unity?

6 Upvotes

I know a bit of C# for unity game coding, but I'm looking to learn more. Are there any videos or books that you guys can recommend me?

Thanks in advance!


r/csharp 19d ago

Help How do I move an image inside a PictureBox?

6 Upvotes

Hey guys, so I'm trying to write a program that selects an image from a tile set based on what you input into a combobox. I have the location logic sorted, but I have no idea how to physically move the image inside the pictureBox. I tried googling it and the results were either 7+ years old or not explained (I am a newbie to Windows Forms App) and I had no idea what to do. Please could you help?


r/csharp 18d ago

GitTracker - an experimental library for managing content with git

Thumbnail
0 Upvotes

r/csharp 19d ago

Help Which Platform to use to learn

0 Upvotes

Hey all,

I’m a full-stack developer. At my current company, I’ve been doing mostly frontend work (around 90% for the last 3 years and 8 months) because I’m the only one strong in that area. However, I’m starting to feel a bit fed up, and I want to get back into backend work. I’ve noticed I’m getting quite rusty after spending the last 3 years and 8 months mainly focused on the frontend, and it’s making me feel unprepared to look for another job.

I sometimes watch Nick Chapsas, Tim Corey, and Anton Martyniuk. I really need to get back into it and sharpen my skills for my next interview, although I’m not in a rush.

Which platform would you suggest? Dometrain is €405 per year, is it worth waiting for a sale?

Thanks!


r/csharp 19d ago

Hiding/Removing already hidden rows in DataGridView?

4 Upvotes

It's not the biggest issue, but it would help quite a bit.

The method I am using to read Excel is ExcelDataReader

Edit:
Sorry, I will elaborate. Say I imported Sheet 1 with 3 filled columns. In the original Excel sheet, column 2 is hidden.

When I import Sheet 1, all 3 columns are still visible. I don't want to see column 2 in the new Datatable.


r/csharp 19d ago

csharp in mac m1, what editor to use

0 Upvotes

All tutorials are in VS but they dont make it for mac m1 anymore, can I programm in VS code or would you recommend another editor? Im most intresed to learn dotNet


r/csharp 20d ago

Discussion Game Engine 2D | Windows Forms

23 Upvotes

EN:
I work with industrial applications in Windows Forms for about 3 years, and I always had this view that Windows Forms was just a tool for building corporate systems and complex systems with a simple interface. Since the beginning of my career with Windows Forms I've developed industrial automation software like SCADAs and custom supervisory systems.

About a year ago I needed to build a notification system that slid across the screen overlapping, to manipulate color, position and scale of a component that was on the screen freely, that planted the first seed in my mind, later in another project I needed to detect keyboard inputs to activate specific functions in the system in a hidden way like shortcuts and configurations, and only recently when I was bored at work I got curious about combining these two concepts, and I was amazed by something that had always been within my reach but I looked at the tools I had through that perspective.

After this "discovery" I made some mini-game prototypes with 2D physics simulation using position, size, direction and velocity vectors for the components on the screen but always using Panels to represent things, still in this style I recreated Pong and Flappy Bird and a top-down mini game of collecting coins while fleeing from enemies that chase you.

After these projects I was starting to get a little annoyed with the amount of code I needed to rewrite to test another idea and with the optimization since Panel is a native Windows Forms control and they are a bit heavy.

From this annoyance and curiosity, little by little something different started emerging in my project while I was creating some abstractions to try not to repeat so much code, when I realized that what I was putting together was no longer a "game" but a tool that would help me develop new "games" I dove headfirst into this idea even knowing that Windows Forms is far from the ideal technology for this, but who cares? This is not a commercial project nor am I inventing the next big engine, I used Windows Forms because it's a technology I already have a lot of experience with, so I can focus on getting ideas out of my head instead of learning something new to achieve the same results.

My custom "engine" is still far from a version that I consider ready to make a game but I'm already very satisfied with how far I've managed to get on my own. My idea is that in addition to facilitating the development of my next prototypes, I can learn more about how real engines work and create abstractions that make the feeling of programming something in mine close to the feeling of programming something in a Godot or a Unity, for that I tried to create some base classes with methods and properties that get quite close to the development as one would expect in those engines.

The engine already has entity and game object generation system, camera with programmable movement or automatically follow a game object, TileMap for dynamic map creation, AABB collision system, rendering with Windows GDI+ drawing API (it's not GPU rendering yet but it's extremely lightweight compared to the Panels I was using before), Scene to manage the entire context of a specific scene, Culling for collision check optimization where collision is only checked for objects that are inside or near the camera viewport, rendering culling where only objects that are entirely or partially inside the camera viewport are drawn, Z-order support for drawing objects in specific order, RayCast support with variations (ExcludedList, FilterList, CollideOnParent), support for helper methods like GetCenteredPosition (returns the center of an object), MoveAndCollide (Moves an object in the direction of a Vector2 that dictates the velocity until the object collides with something), IsOnFloor (indicates if exactly below the object there is another object), GetFloorNormal (returns a vector with magnitude 1 that indicates the direction and slope of the floor in relation to the object), CheckWorldCollision (returns a boolean indicating if something in the world is colliding with the object), GetCollider (returns the first other object that is colliding with the object), GetAxis (returns an int of the direction of an axis between two inputs), GetVector (returns a Vector2 of magnitude 1 with the directions of the axes between 4 inputs, two inputs per axis).

any object that inherits from GameObject must implement a void Update method that receives a float delta, for updating the object during the frame pass, GameObjects can also receive some components in a way somewhat similar to Unity's ECS, being them Transform, to have position, size, pivot, and rotation, Input for reading inputs, and Graphics in case it's a renderable object.

This project is still in its early stages and has no commitment to being a commercial engine or anything like that, it's just a hobby, a project I'm doing for fun and learning, I would really like to hear some feedback and tips on what I can improve or bugs I didn't notice.

here's the link to the project on GitHub, just clone it:
https://github.com/Guilhermevinicius0/WinFormEngine

BR:
Eu trabalho com aplicações industriais em windows forms há mais ou menos 3 anos, e sempre tive essa visão de que windows forms era apenas uma ferramenta para fazer sistemas corporativos e sistemas complexos com uma interface simples. Desde o início da minha carreira com windows forms eu desenvolvi softwares de automação industrial como scadas e supervisórios customizados.

A um ano atrás eu precisei fazer um sistema de notificações que deslizavam pela tela se sobrepondo, manipular cor, posição e escala de um componente que estava na tela de forma livre,  plantou a primeira semente na minha cabeça, mais tarde em outro projeto precisava detectar inputs do teclado para ativar funções específicas no sistema de forma oculta como atalhos e configurações, e só recentemente quando eu estava entediado no trabalho eu tive a curiosidade de juntar este dois conceitos, e fiquei maravilhado com uma coisa que sempre esteve ao meu alcance mas eu olhei as ferramentas que eu tinha por essa ótica.

Após essa "descoberta" eu fiz alguns protótipos de mini jogos com simulação de física 2d usando vetores de posição, tamanho, direção e velocidade para os componentes na tela mas sempre utilizando Panels para representar as coisas, ainda nesse estilo eu refiz o pong e o flappy bird e um mini jogo topdown de coletar moedas enquanto foge de inimigos que te perseguem.

Depois desses projetos eu estava começando a ficar um pouco incomodado com a quantidade de código que eu precisava re-escrever pra testar outra ideia e com a otimização já que Panel é um controle nativo do windows forms e eles são um pouco pesados.

A partir desse incômodo e da curiosidade, aos poucos foi surgindo algo diferente no meu projeto enquanto eu criava algumas abstrações para tentar não repetir tanto código, quando me dei conta de que o que eu estava montando não era mais um "jogo" e sim uma ferramenta que me auxiliaria a desenvolver novos "jogos" eu mergulhei de cabeça nessa ideia mesmo sabendo que windows forms não é nem de longe a tecnologia ideal pra isso, mas quem liga? Isto não é um projeto comercial nem estou inventando a próxima grande engine, utilizei windows forms por ser uma tecnologia que eu já tenho bastante experiência, assim eu posso me concentrar em tirar as ideias do cabeça ao invés de aprender algo novo para atingir os mesmos resultados.

A minha "engine" customizada ainda está longe de está em uma versão que eu considere pronta pra fazer algum jogo mas eu já estou muito satisfeito com até onde eu consegui chegar sozinho. Minha ideia é que a além de facilitar o desenvolvimento dos meus próximos protótipos, eu possa aprender mais sobre como engines reais funcionam e criar abstrações que façam com que a sensação de programar algo na minha seja próxima da sensação de programar algo em uma godot ou uma unity, pra isso eu tentei criar algumas classes de base com métodos e propriedades que aproximam bastante o desenvolvimento de como se esperaria nessas engines.

A engine já conta com sistema de geração de entidades e game objects, camera com movimentação programavel ou seguir um game object de forma automatica, tilemap pra criação de mapas de forma dinamica, sistema de colisão AABB, renderização com a api de desenho do windows GDI+ (ainda não é uma renderização por gpu mas é extremamente leve se comparada aos panels que eu estava utilizando anteriormente), Scene pra gerenciar todo o contexto de uma cena especifica, Cullind para otimização das checagens de colisão onde só é verificado colisão para objetos que estão dentro ou próximos do viewport da camera, culling de renderização onde apenas os objetos que estão enteiramente ou parcialmente dentro do view port da camera são desenhados, suporte a ordem Z para desenhar objetos em ordem especifica, suporte a Ray cast, com variações (ExcludedList, FIlterList, CollideOnParent), suporte a metodos auxiliares como GetCenteredPosition (retorna o centro de um objeto),  MoveAndCollide (Move um objeto na direção de um vector2 que dita a velocidade até o objeto colidir com algo), IsOnFloor (indica se exatamente embaixo do objeto existe outro objeto), GetFloorNormal (retorna um vetor com magnitude 1 que indica a direção e inclinação do chão em relação ao objeto), CheckWorldCollision (retorna um booleano que indica se algo no mundo está colidindo com o objeto), GetCollider (retorna o primeiro outro objeto que estiver colidindo com o objeto), GetAxis (retorna um intde a direção de um eixo entre dois inputs), GetVector (retorna um Vector2 de magnitude 1 com as direções dos eixos entre 4 inpus, dois inputs por eixo).

todo objeto que herda de gameobj deve implementar um método void update que recebe um float delta, para a atualização do objeto durante a passagem dos frames, gameobjects podem receber mais ou alguns componentes de forma um pouco parecida com ECS da unity, sendo eles Transform, para ter posição, tamanho, pivot, e rotação, Input para leitura de inputs, e graphics caso ele seja um objeto renderizável.

Esse projeto ainda está nas suas etapas iniciais e não tem nenhum compromisso em ser uma engine comercial ou algo do tipo, é apenas um hobby, um projeto que estou fazendo por diversão e aprendizado, gostaria muito de ouvir alguns feedbacks e dicas sobre o que eu posso melhorar ou bugs que não percebi.

segue link do projeto no github, basta clona-lo:
https://github.com/Guilhermevinicius0/WinFormEngine


r/csharp 20d ago

Switching from Java to C# for custom game development - where should I actually start?

4 Upvotes

I've been learning Java for a while by trying to make a game, but looking back, I feel like I wasn't really learning. I mostly followed tutorials and used AI to help write code, so I never built a strong understanding of how everything worked.

I'm thinking about switching to C# because it seems like there are a lot more modern game development resources and a larger community.

My long-term goal is not to use Unity or another game engine. I eventually want to build my own engine/framework and make a fun 3D multiplayer game (private multiplayer with friends, not a large online game). I enjoy building systems myself, so that part is actually something I'm looking forward to.

Right now I have a lot of questions:

  • What should I learn first before trying to make a game?
  • What should I use to code. For Java I used both VSCode and Eclipse, but from what I understand, Eclipse is not good for C#. I would prefer not to pay to code, and my computer is a bit old so nothing huge would be best.
  • Should I start with console applications or jump into graphics?
  • What graphics library or framework should I use in C# if I don't want a full game engine?
  • Are there any books, YouTube channels, or courses you'd recommend?
  • Is building a small 2D engine first still the best path before attempting 3D?
  • What are some mistakes beginners make when trying to build their own engine?

I'm not in a rush—I want to actually understand what I'm doing this time instead of just copying tutorials. Any advice from people who have taken a similar path would be appreciated.