开发者
What MasterMemory Solves—and What It Doesn't: A Practical Guide to Static Game Data in Unity
Introduction When you build games with Unity, you eventually run into the problem of managing static game data—often called master data in Japanese game development. At first, ScriptableObject may be more than enough. If your project has a few dozen items, a few dozen enemies, and only a small number of stage definitions, ScriptableObject is convenient because you can inspect and edit everything directly in the Unity Editor. As the project grows, however, the situation changes. You may end up with tables for items, characters, skills, quests, rewards, shops, gacha pools, stages, enemy placements, progression curves, and localization text. The data is no longer edited only by programmers. Planners and game designers may need to work with it in Excel or Google Sheets. At that point, the problem is no longer just choosing a file format. You need to think about questions such as: How do you load a large amount of data quickly? How do you write ID lookups and composite-key queries safely? Should CSV or JSON be parsed directly at runtime? Is it reasonable to create a large number of Dictionaries? How do you validate references between tables? How do you debug data after converting it to binary? How do you connect the source data edited by planners to the data loaded by Unity? For the runtime loading and lookup part of that problem, one strong option is Cysharp's MasterMemory . The official README describes MasterMemory as a “Source Generator based Embedded Typed Readonly In-Memory Document Database” for .NET and Unity. In practical terms, you define your schema as C# types, a Source Generator creates a typed read-only in-memory database API, and the application loads MessagePack binary data that can be queried through type-safe methods. The official README highlights performance compared with SQLite, low allocation during queries, a small database size, and generated database structures that are type-safe and IDE-friendly. Cygames Engineers' Blog also has useful articles
AI 资讯
Building a tiny Windows tray app with .NET 9 Native AOT and raw Win32
I built CreditMeter, a small Windows tray app that shows GitHub Copilot AI-credit usage like a taxi meter. Why I built it Agentic coding makes AI usage feel invisible until you look at the bill. Constraints no WinForms no WPF no backend no telemetry no dependency-heavy architecture Tech stack C# / .NET 9 Native AOT raw Win32 / PInvoke GitHub REST API DPAPI for local PAT storage What I learned For tiny tools, architecture is also about knowing what not to add. Repo https://github.com/cdilorenzo/CreditMeter
AI 资讯
Stop writing a test-data builder for every class in .NET
If you've ever written test data by hand, you know the ritual: a PersonBuilder , an OrderBuilder , an AddressBuilder … one hand-written builder per class, each one a wall of WithX(...) methods you have to maintain forever. The Test Data Builder and Object Mother patterns are great — the boilerplate is not. XModelBuilder gives you a fluent builder for any C# class out of the box. No per-class builder required. It handles constructor parameters, init-only properties, read-only members, even private backing fields — via reflection, deterministically. Install dotnet add package XModelBuilder 30-second example You can use it fully standalone (no DI container) through a small static facade: using XModelBuilder.Default ; var order = For . Model < Order >() . With ( x => x . OrderDate , new DateTime ( 2026 , 7 , 1 )) . With ( x => x . Lines [ 0 ]. Product , "Widget" ) // deep paths + indexers just work . With ( x => x . Lines [ 0 ]. Quantity , 3 ) . Build (); No OrderBuilder , no OrderLineBuilder . The Lines[0].Product path drills into a nested collection element and sets it for you. Need a whole list? Create.Models<Order>(10) . Deterministic fakers, seeded once Random test data that changes every run is a debugging nightmare. XModelBuilder ships a seeded, dependency-free faker (and a Bogus integration if you prefer). Register it once: services . AddXModelBuilder () . AddXFaker ( seed : 12345 ); // reproducible values, every run Then let it fill in the noise while you set only what your test actually cares about: var order = xprovider . For < Order >() . With ( x => x . Id , p => p . XFake (). NewGuid ()) . With ( x => x . Customer . Name , p => p . Bogus (). Company . CompanyName ()) . With ( x => x . Lines [ 0 ]. Quantity , 3 ) . Build (); XFake().NewGuid("customer-acme") even gives you a stable GUID from a name — same key, same GUID, regardless of call order or parallelism. Deterministic by design. Build a whole list: BuildMany Need ten of something, each slightly differ
AI 资讯
10 Common Unity Networking Issues (and How to Fix Them)
Multiplayer bugs in Unity rarely look like networking bugs. They look like "the game froze," "the player teleported," or "it worked in the Editor and broke in the WebGL build." By the time you've traced it back to the actual cause, you've usually burned an afternoon. Here are 10 issues that show up constantly in Unity networking code — WebSocket-based, Socket.IO, or otherwise — with the actual root cause and the fix. A few of these come straight out of real regression tests and commit history in socketio-unity , an MIT-licensed Socket.IO v4 client for Unity. The rest are patterns you'll recognize if you've shipped a multiplayer game. 1. Reconnect wipes your room/namespace state Symptom: Connection drops for two seconds, comes back, and the player is no longer in their room/lobby/channel — even though the server never removed them. Cause: A common (bad) reconnect implementation tears down the whole client and rebuilds it from scratch — including the list of channels/namespaces the player had joined. The reconnect "succeeds" at the transport level but silently drops application-level state. Fix: Reconnect logic should preserve subscriptions across the transport reset and only re-emit join / connect for namespaces the client already had open. If you're rebuilding the socket object on every reconnect attempt, stop — reconnect the transport, keep the namespace map. // Wrong: rebuilds everything, loses namespace state void OnReconnect () => CreateFreshEngine (); // Right: reuses the existing namespace map void OnReconnect () => ReconnectEngine (); // _namespaces untouched 2. "get_gameObject can only be called from the main thread" Symptom: Random UnityException thrown from inside a network event handler, but only sometimes — usually right when the server sends something. Cause: Your WebSocket/network library delivers callbacks on its own I/O thread. Any Unity API call ( transform.position = , Instantiate , even some Debug.Log paths) from that thread throws. Fix: Never tou
AI 资讯
ASP.NET Core: Building High-Performance Web Applications and APIs
ASP.NET Core: Building High-Performance Web Applications and APIs A practical guide to ASP.NET Core — the cross-platform framework for building REST APIs, MVC applications, and backend services on .NET, covering architecture, minimal APIs, middleware, performance, and modern patterns. Table of Contents Introduction Architecture Overview Minimal APIs MVC and Controllers Middleware Pipeline Dependency Injection Configuration and Options Authentication and Authorization Performance Features Testing and Observability Quick Reference Table Conclusion Introduction ASP.NET Core is a free, open-source, cross-platform framework for building web apps, APIs, and backend services. It's a ground-up rewrite of the original ASP.NET, designed around three priorities: Performance — it's consistently one of the fastest mainstream web frameworks in independent benchmarks (e.g., TechEmpower). Modularity — you opt into only the middleware and services your app actually needs, instead of a fixed, heavyweight pipeline. Cross-platform — runs identically on Windows, Linux, and macOS, and deploys to containers, serverless, or bare metal. This guide covers the core building blocks you'll use in almost any ASP.NET Core project, from a five-line minimal API to a full MVC application with authentication and background services. 1. Architecture Overview Every ASP.NET Core app starts from a unified entry point — Program.cs — using the minimal hosting model introduced in .NET 6. var builder = WebApplication . CreateBuilder ( args ); // Register services (dependency injection container) builder . Services . AddControllers (); builder . Services . AddEndpointsApiExplorer (); builder . Services . AddSwaggerGen (); var app = builder . Build (); // Configure the HTTP request pipeline (middleware) if ( app . Environment . IsDevelopment ()) { app . UseSwagger (); app . UseSwaggerUI (); } app . UseHttpsRedirection (); app . UseAuthorization (); app . MapControllers (); app . Run (); Two phases matter here:
AI 资讯
Modern C# Features: A Deep Dive into Records, Pattern Matching, Async, and Performance
Modern C# Features: A Deep Dive into Records, Pattern Matching, Async, and Performance A practical guide to the C# language features that have reshaped how we write .NET code — records, pattern matching, async/await improvements, nullable reference types, LINQ enhancements, Span<T> , and performance optimizations. Table of Contents Introduction Records Pattern Matching Async/Await Improvements Nullable Reference Types LINQ Enhancements Span<T> and Memory<T> Performance Optimizations Quick Reference Table Conclusion Introduction C# has evolved significantly since C# 8. Each release (9, 10, 11, 12, 13) has focused on three consistent themes: Conciseness — write less boilerplate to express the same intent. Safety — catch bugs at compile time instead of runtime (especially around null ). Performance — give developers low-level control without leaving the managed, safe world of .NET. This guide walks through the features that matter most in day-to-day development, with working code examples you can drop into a dotnet run project. 1. Records Introduced in C# 9 , record types give you immutable, value-based data models with almost no ceremony. Why records exist Before records, representing an immutable data object meant hand-writing a constructor, Equals , GetHashCode , ToString , and often a With -style copy method. Records generate all of this for you. // Before: a "plain" immutable class public class PersonClass { public string FirstName { get ; } public string LastName { get ; } public PersonClass ( string firstName , string lastName ) { FirstName = firstName ; LastName = lastName ; } public override bool Equals ( object ? obj ) => obj is PersonClass p && p . FirstName == FirstName && p . LastName == LastName ; public override int GetHashCode () => HashCode . Combine ( FirstName , LastName ); public override string ToString () => $"PersonClass {{ FirstName = { FirstName }, LastName = { LastName } }} " ; } // After: the same thing as a record public record Person ( stri
AI 资讯
LINQ and ZLinq in the Unity 6 Era: Avoiding GC Allocations in Large-Scale Projects
Introduction In large-scale Unity development, GC Alloc can quietly become a real problem. At first, nothing looks wrong. But as the project grows and you add more enemies, UI, master data, events, states, notifications, logs, and other systems, small allocations that happen every frame begin to pile up. LINQ is especially convenient. var aliveEnemies = enemies . Where ( x => x . IsAlive ) . OrderBy ( x => x . DistanceToPlayer ) . ToList (); It is readable. But if this kind of code runs every frame, it can become a source of both GC Alloc and CPU overhead. Unity's official documentation also recommends reducing frequent managed heap allocations as much as possible, ideally getting close to 0 bytes per frame. https://docs.unity3d.com/2022.3/Documentation/Manual/performance-garbage-collection-best-practices.html For general GC Alloc best practices, this article refers to the Unity 2022.3 documentation, because the general guidance still applies. Unity 6-specific GC behavior is covered later using the Unity 6.0 documentation. This article assumes Unity 6.0 as the minimum Unity version and explains how to choose between regular LINQ and ZLinq in production code. Unity 6.0 uses the Roslyn C# compiler, and its C# language version is C# 9.0. However, some C# 9 features, such as init-only setters, are not supported. https://docs.unity3d.com/6000.0/Documentation/Manual/csharp-compiler.html The short version The point of this article is not to ban LINQ completely. Do not use LINQ in hot paths just because it is readable. Do not assume ZLinq solves everything just because you introduced it. Those are the two main ideas. A rough guideline looks like this: Area Guideline Editor extensions, build scripts, debug code Regular LINQ is usually fine Startup, loading, initialization LINQ can be fine, but measure when data size is large Update / LateUpdate / FixedUpdate Avoid LINQ by default Code that is not per-frame but still called frequently Consider ZLinq Code that materializes res
AI 资讯
Back to Simplicity: Why We Built CALM, a Lock-Free Single-Thread Messaging Library for .NET
Hello everyone! For many years, I have been developing equipment control software and long-term support products using .NET/C#. Based on the experiences gained through working with various development teams, I would like to talk about why I created CALM (Cooperative Async Lock-free Messaging) , an open-source library for .NET. The Magic of UI Thread + Event-Driven + async/await My journey with .NET/C# began around the days of .NET Framework 4.0. At the time, code-behind in Windows Forms was incredibly intuitive. It allowed me to join the development team and become productive in a very short period. Back then, executing time-consuming operations on a separate thread and returning the results to the UI thread via callbacks was painful and error-prone. However, the introduction of async/await in .NET Framework 4.5 completely shifted the paradigm. The SynchronizationContext magically handled thread marshaling behind the scenes, and our code became amazingly simple. "Running asynchronous operations safely on a single thread (the UI thread) via an event-driven approach" — this seamless developer experience was my starting point. Divide and Conquer, Dependency Management, and CQS As our product evolved, the codebase grew, and the development team expanded beyond a certain size. Suddenly, the software became exponentially complex. Following industry best practices, we introduced MVP and MVVM patterns to separate the UI from the business logic. We also refactored our domain models based on Domain-Driven Design (DDD) and Clean Architecture principles, alignment with the team's domain knowledge. While this helped organize the logic within individual models, it introduced a new nightmare: complex dependencies between models. We struggled heavily with initialization, especially with models that had circular or mutual dependencies. To break this web of tight coupling, we introduced a mechanism that combined the Observer pattern (inspired by Android's EventBus) with the philosoph
AI 资讯
Data-Oriented Design in C#: Why Objects Are Slowing You Down
Data-Oriented Design in C#: Why Objects Are Slowing You Down In my previous article, we talked about starving the Garbage Collector by moving away from heap-allocated class types and leaning heavily into struct , Span<T> , and ArrayPool<T> . That’s a critical first step, but it only solves half the problem. You’ve stopped the GC from pausing your app, but you might still be leaving massive amounts of CPU performance on the table. Why? Because of how your data is structured. It’s time to talk about Data-Oriented Design (DoD) . The Object-Oriented Trap We are taught from day one to model our code after the real world. If you are building a social network graph, you might write something like this: public class UserNode { public int Id { get ; set ; } public string Name { get ; set ; } public List < Edge > Connections { get ; set ; } } public class Edge { public UserNode Target { get ; set ; } public int Weight { get ; set ; } } This makes perfect logical sense. A user has connections, and those connections point to other users. But modern CPUs don't care about your logical models. A CPU only cares about reading data from memory into its L1/L2 caches as fast as possible. When a CPU reads a byte from RAM, it doesn't just read that one byte; it pulls a whole 64-byte "cache line" under the assumption that you will probably want the neighboring bytes next. When you loop through a List<UserNode> , traversing from object to object, you are jumping randomly across the heap. The CPU pulls a cache line, reads your data, and then has to go fetch a completely different block of RAM for the next node. This is called pointer chasing , and the resulting cache misses are devastating to performance. Enter Data-Oriented Design: Struct of Arrays (SoA) Data-Oriented Design says: Stop modeling the real world. Model the data the way the hardware wants to consume it. Instead of an Array of Structs (AoS) (or an array of objects), we invert the architecture to a Struct of Arrays (SoA) . If we
AI 资讯
Clean Architecture in .NET 8: A 2026 Starter Template with 4 Projects, EF Core, and JWT Auth
I joined a team where the controller was 800 lines long, the business rules were scattered between the controller and the DbContext , and "to run the tests, spin up a SQL Server in Docker" was a sentence I heard every week. The fix was Clean Architecture. The argument I had with the team lead was about how to actually structure it. We argued for two weeks. Then I built this template so the next person wouldn't have to. This is the Clean Architecture .NET 8 starter template I wish someone had handed me on day one. Four projects, strict dependency direction, domain entities that own their own invariants, and an Application layer you can unit test with Moq — no database required. The whole repo is on GitHub , MIT-licensed, runs with dotnet run , and ships with xUnit tests, JWT auth, Swagger, Docker, and CI. This post is the explanation of why each project exists, what goes in it, and what I learned the hard way about getting Clean Architecture right in .NET. The problem Clean Architecture solves The naive way to build a .NET Web API is one project, one folder structure, and "everything talks to everything": MyApp/ Controllers/ ProductsController.cs ← HTTP stuff OrdersController.cs ← HTTP stuff + business rules Services/ ProductService.cs ← business rules + DbContext.SaveChanges Data/ AppDbContext.cs ← EF Core, entities Models/ Product.cs ← POCO with public setters This works for the first 1,000 lines. By 5,000 lines, the controller is doing five things at once. By 10,000, "to test this, I need a database" is the answer to every test question, and your CI takes 20 minutes because every test run spins up SQL Server. Clean Architecture says: separate the business rules from the HTTP boundary, separate the database from the business rules, and enforce it with project references. A controller is allowed to call a service. A service is allowed to call a repository. A repository is allowed to know about EF Core. Nothing is allowed to know about anything "above" it in the chai
AI 资讯
Build a Local RAG Chatbot in 30 Minutes with .NET 8, Ollama, and React
I uploaded a 40-page PDF of an internal API spec, asked "what's the rate limit for the search endpoint?", and got back: "100 requests per minute per API key, with bursts up to 200. See section 4.2 of the document." With citations. In about three seconds. The whole stack runs on my laptop. It cost me $0 in LLM credits during development because Ollama is free and local, and the embedder I used is also free and local. The repo is here — issues and PRs welcome. This is the build log. Not a tutorial where every step works the first time — a build log where I tell you which decisions held up and which ones I redid. The problem most "chat with your PDF" demos have Every "chat with your PDF" tutorial I read in early 2025 had the same shape: open OpenAI, paste your API key, call gpt-4 with a 50-page PDF stuffed into the context window, get an answer, pay $0.03 per question, repeat. That works for a demo. It does not work for a tool you'd actually use at work, because: The PDF might contain customer data, internal pricing, or unreleased features. You do not want that going to OpenAI's training pipeline or anyone's logs. The cost adds up. If your team uses it 50 times a day, that's $45/month per seat. The model hallucinates on long PDFs anyway. Stuff 100 pages into a 128k context window and the model starts forgetting the middle. The fix is RAG (Retrieval-Augmented Generation) — don't send the whole PDF, send only the 3-5 chunks that are actually relevant to the question. The rest of the work is the same: embed the chunks, embed the question, find the closest matches, send those to the LLM with the question. But the cost and the privacy story both improve by 100x. The actual ask: Upload a PDF. Ask questions. Get answers from the document with citations, in under 5 seconds, with no data leaving my laptop and no monthly bill. The architecture One .NET 8 solution, one React app, one Ollama process, zero cloud dependencies. [ PDF Upload ] | v +-------------------+ chunks +-------
AI 资讯
From Stack Trace to Suggested Fix in 4 Seconds: Building a Self-Healing .NET API Gateway.
Last Tuesday my API gateway caught a NullReferenceException , streamed it to a dashboard in real-time, and pushed a draft code fix to the browser tab of the on-call engineer — before I finished reading the error myself. That sentence used to be vendor marketing. Now it's just my Program.cs . This is the architecture post-mortem. I built it on weekends. It runs in Docker. It cost me exactly $0 in LLM credits during development because Groq's free tier is generous and Ollama works as a swap-in. The repo is here — issues and PRs welcome. The problem most .NET teams have Production errors are caught, logged to a file, and forgotten. Engineers find out from a Slack ping twenty minutes later, if at all. By the time someone looks, the original request context is gone, the user's session has expired, and the stack trace is buried four layers deep in System.* calls. "Self-healing" is a word vendors use to mean "auto-restart the pod." I wanted something better. The actual ask: When an exception is thrown in service A, give the engineer (a) a clear root cause, (b) a suggested fix, and (c) a draft code patch — in under 30 seconds. Not a magic black box. Not an auto-applied patch. Just: catch the error, give the model the right context, push the analysis to a human in real-time, and let the human close the loop. The architecture One .NET solution, four projects, four NuGet packages, no new infrastructure beyond what you probably already have. [ HTTP request ] | v +-------------------+ enqueue +---------------------+ | SmartLogAnalyzer. | ---------------------> | Hangfire (Redis) | | Api | +----------+----------+ | (ErrorHandling | | | Middleware) | v +-------------------+ +---------------------+ | SmartLogAnalyzer. | | Worker | | (ErrorProcessingWorker) +-----+-------+-------+ | | AI call | | persist v v +-----------+ +-----------+ | Semantic | | MSSQL | | Kernel + | | (ErrorLog | | Groq LLM | | table) | +-----+-----+ +-----------+ | v +---------------------+ | SignalR Hub | | (
AI 资讯
Already using LaunchDarkly or Flagsmith? Here's how to try FtrIO on a single flag
Thinking about trying FtrIO? The new CLI makes it easy to start with just one feature flag If you've been curious about FtrIO (the .NET feature toggle library that replaces if (featureFlags.IsEnabled(...)) with a [Toggle] attribute woven directly into your compiled IL) but weren't sure where to start, the experimental release of FtrIO.onetwo just made that first step a lot smaller. You don't need to commit to a full migration. You don't need to rip out your existing flag library. You just need one method and 20 minutes. What FtrIO.onetwo does FtrIO.onetwo is a .NET CLI audit tool. Its default mode scans your source tree, finds every FtrIO toggle reference, and tells you exactly what's live right now: dotnet tool install --global FtrIO.onetwo --version 1.1.1-experimental ftrio.onetwo --source C: \P rojects \M yApp But in this experimental release it does two new things: ftrio.onetwo import : pulls your current flag state from LaunchDarkly, Flagsmith, flagd, environment variables, or an HTTP endpoint directly into appsettings.json . Your existing flag library keeps working unchanged. ftrio.onetwo migrate : scans your .cs files for LaunchDarkly or Flagsmith SDK call patterns using Roslyn, cross-references them against your live flag state, and generates a report showing exactly what each flag would look like in FtrIO and how to migrate it. The "try it on one flag" workflow The migrate report categorises every flag it finds: ✅ Ready to migrate : boolean flag, no targeting rules, straightforward [Toggle] replacement ⚠️ Needs review : targeting rules, number flags, needs a decision ❌ Cannot migrate : JSON flags, recommend moving to IConfiguration For every ready flag it shows the suggested refactor. Something like: new - checkout - flow → NewCheckoutFlow File : Services \ OrderService . cs : 42 Current code : if ( client . BoolVariation ( "new-checkout-flow" , user , false )) { ValidateCart (); ApplyDiscounts (); ProcessPayment (); } Suggested action : Extract the if bloc
AI 资讯
This week in Cursor + .NET — 7 rules (week ending June 21, 2026)
Every weekday a single, opinionated rule for senior C#/.NET engineers using Cursor. Here's the full week in one read — canonical posts live on the Agentic Architect blog . 7 daily senior rules Rule 14: Sealed By Default Sun 21 Jun Mark every class sealed unless inheritance is explicitly planned. Stops Cursor inventing accidental inheritance hierarchies "for flexibility." Small but measurable virtual-call perf wins too. → Permalink on the blog Rule 13: Strongly-Typed IDs Sat 20 Jun OrderId as record struct OrderId(Guid Value) beats raw Guid everywhere. Stops the AI passing a CustomerId where an OrderId was expected — a bug the compiler can't catch with primitive obsession but catches instantly with domain primitives. → Permalink on the blog Rule 12: IOptionsSnapshot Over Raw Config Fri 19 Jun Business code should never call IConfiguration directly. Strongly-typed IOptions or IOptionsSnapshot bindings only. The AI loves to "just grab the config value" — refuse it and force a settings class with validation attributes. → Permalink on the blog Rule 11: Rethrow, Don't throw ex Thu 18 Jun throw ex resets the stack trace. throw preserves it. Cursor gets this wrong about 40 percent of the time when generating catch blocks. Rewrite any naked throw ex to throw unless the exception has been explicitly wrapped. → Permalink on the blog Rule 10: AsNoTracking for Reads Wed 17 Jun Every read-only EF Core query should call AsNoTracking. Add a rule that recognises query methods returning DTOs (not entities) and inserts the call. Cursor never does this by default and your read perf degrades silently across releases. → Permalink on the blog Rule 9: Scoped Capture in Singleton Tue 16 Jun The single most expensive .NET runtime bug: a Singleton holding a Scoped service. Cursor cheerfully writes this without warning. Audit constructor parameters of any class registered as Singleton — if any are typically Scoped (DbContext, repositories, MediatR sender), flag it before merge. → Permalink on
AI 资讯
Generics in C# (List , Dictionary )
Originally published at https://allcoderthings.com/en/article/csharp-generics-list-t-dictionary-tkey-tvalue In C#, generics are used to increase type safety and flexibility. Generic classes and collections eliminate the need for runtime type casting and avoid unnecessary boxing and unboxing operations, improving performance and reducing the risk of errors. Before generics were introduced, collections such as ArrayList stored elements as object . When a value type like int was added to an ArrayList , it had to be boxed (converted to object ), and later unboxed when retrieved. This boxing/unboxing process caused additional memory allocations and performance overhead. With generic collections like List<T> and Dictionary<TKey,TValue> , elements are stored in their actual types, eliminating these costs and making the code both safer and faster. List List<T> is a generic collection that dynamically stores elements of a specific type. T specifies the type of elements the list will contain. using System ; using System.Collections.Generic ; var numbers = new List < int >(); numbers . Add ( 10 ); numbers . Add ( 20 ); numbers . Add ( 30 ); foreach ( int n in numbers ) Console . WriteLine ( n ); // Output: // 10 // 20 // 30 Note: Unlike arrays, List<T> can grow and shrink dynamically. Dictionary Dictionary is a generic key–value collection. TKey specifies the type of the key, and TValue specifies the type of the value. using System ; using System.Collections.Generic ; var students = new Dictionary < int , string >(); students [ 101 ] = "John" ; students [ 102 ] = "Mary" ; students [ 103 ] = "Michael" ; foreach ( var kv in students ) Console . WriteLine ( $" { kv . Key } → { kv . Value } " ); // Output: // 101 → John // 102 → Mary // 103 → Michael Note: Each Key in a dictionary must be unique. Attempting to add the same key again will cause an error. Creating Your Own Generic Classes You can also define your own generic types, not just use built-in collections. This allows you
AI 资讯
Agent Framework RAG for Agents: Giving Your Agent the Right Context
This is Part 13 of my series on the Microsoft Agent Framework. You can read the original post over on lukaswalter.dev . In the previous article , we looked at workflows. Workflows make sense when the process itself needs structure: state, checkpoints, events, human approvals, and resumable execution. This post is the bridge from Agent Framework into RAG. I plan on doing a full RAG deep dive sometime later. The practical question for now is smaller: How do I connect an Agent Framework agent to private application knowledge without stuffing every document into the prompt? For agents, RAG is less about adding more text and more about giving the agent a controlled retrieval path. The agent should fetch the right context at the point where it needs it. Agents do not know your private data Your company documents, product catalog, tickets, rules, policies, runbooks, and internal knowledge base live outside the model. The model has generic knowledge. Your application has private knowledge. Treat those as separate systems. You can paste some private data into the prompt, and for a demo that may be enough. But this falls apart quickly: full documents are expensive to send repeatedly long prompts are fragile stale documents may sit next to current ones users may not be allowed to see every source long context still needs selection The last point is easy to underestimate. A larger context window lets you send more text. It does not decide which text is correct, current, relevant, or permitted. Do not give the agent all knowledge. Give it the right context at the moment it needs it. Retrieval owns that job. The minimal RAG shape The basic RAG loop is small: user question -> retrieve relevant chunks -> pass chunks to the agent -> agent answers using that context For documents, the longer pipeline usually looks like this: documents -> chunks -> embeddings -> vector store -> search -> retrieved context -> agent response Documents are split into smaller chunks. Those chunks are embe
AI 资讯
Class, Record and Struct in C#
Class, Record, and Struct serve as blueprints for creating new objects. Classes Classes are the foundational building blocks of Object-Oriented Programming (OOP). Blueprint and instance // blueprint public class Person { public int ID { get ; set ; } public string Name { get ; set ; } } // instance var p = new Person { ID = 1 , Name = "Mirza" } Inspection Printing the class instance in the console will just display it's name: var p1 = new Person { ID = 1 , Name = "Mirza" }; Console . WriteLine ( p1 ); // Person To print the actual, we'd need print each property explicitly: Console . WriteLine ( p1 . ID ); // 1 Console . WriteLine ( p1 . Name ); // "Mirza" Mutation C# classes are mutable, meaning the originally set values can be altered: var p1 = new Person { ID = 1 , Name = "Mirza" }; Console . WriteLine ( p1 . Name ); // "Mirza" p1 . Name = "Armin" ; Console . WriteLine ( p1 . Name ); // "Armin" That said, this can be tweaked by changing the accessor the class property. public class Person { public int ID { get ; set ; } public string Name { get ; init ; } // <-- } This time around if we try to change the value of the Name property after initialization, the C# compiler will start to complain. var p1 = new Person { ID = 1 , Name = "Mirza" }; p1 . Name = "Edis" ; // ❌ The init accessor allows you to create properties that can only be assigned a value during object initialization. Memory location Classes are reference types and are allocated on the heap. If we create two distinct class objects and assign one to the other, both objects will point to the exact same reference in memory: var p1 = new Person { ID = 1 , Name = "Mirza" }; var p2 = new Person { ID = 2 , Name = "Mirza" }; p1 = p2 ; p1 . Name = "Sead" ; Console . WriteLine ( p1 . Name ); // Sead Console . WriteLine ( p2 . Name ); // Sead If we change a value in one of the objects, it will be reflected in both. Equality Two class instances (objects) aren't equal even if they share the same values: var p1 = new P
AI 资讯
I Built a Spaced Repetition Flashcard App and Deployed It to Azure for $5/month
A couple of years ago, I built a custom flashcard app. I had a huge list of words and sentences in Japanese that I collected in an Excel file. I wanted an app that could easily take them and display them on flashcards. The flashcard app was useful, but the main issue was that I could only use it on my laptop. This meant that when I wasn't home, I had no access to it. I made some updates so that I could deploy it to Azure and now I can use it on the train or at the park. I wanted to share the app and lessons learned during development. What It Does The app is a straightforward spaced repetition flashcard tool. You create collections, fill them with cards (front/back/optional notes), and review them. After each card you rate your recall: Button Meaning Easy Remembered without effort Good Remembered correctly Hard Remembered with difficulty Again Forgot (resets to day 1) Ratings feed the SM-2 algorithm, which is the same algorithm as other popular spaced repetition apps like Anki. Cards that are easy get pushed further and further into the future. Cards that are difficult will come back sooner. After a while, you're just reviewing what you actually need to review. There's also a 45-second timer per card. If it expires before you complete the card, it automatically counts as Again (Resets to day 1). Before the timer, I found it easy to lose focus or open another tab and forget about the current card. This has helped me stay focused for longer and stay on this task. The CSS is specifically designed to be mobile friendly. The Tech Stack Frontend: Blazor WebAssembly (.NET 10) Backend: ASP.NET Core minimal API (.NET 10) Database: Azure SQL (Basic DTU tier) Hosting: Azure Static Web Apps (frontend) + Azure App Service F1 free tier (backend) I mostly use C# at work, so Blazor WASM was a natural fit. The whole app shares models and flows together without jumping between languages. Importing Cards from Excel This Excel import function is one of the main reasons I made this app.
AI 资讯
The Interval Is the Thing: Modelling Range Types as First-Class Domain Objects in .NET
A complete solution: expressive range types in your domain layer, full PostgreSQL translation in your data layer - no compromises at either end The Two-Column Trap Almost every developer has written it at least once. An object with two date properties: public class MemberSubscription { public int Id { get ; set ; } public int MemberId { get ; set ; } public DateTime StartDate { get ; set ; } public DateTime EndDate { get ; set ; } } Imagine you need to answer a seemingly simple question in a booking system: "Is this subscription still active, and does it conflict with the proposed new one?" With two bare fields, that code ends up looking something like this: // With two bare DateTime fields — the check you always end up writing public static bool IsActive ( MemberSubscription sub , DateTime at ) => sub . StartDate <= at && ( sub . EndDate == default || sub . EndDate > at ); public static bool ConflictsWith ( MemberSubscription a , MemberSubscription b ) { // Partial overlap: a starts inside b if ( a . StartDate >= b . StartDate && a . StartDate < b . EndDate ) return true ; // Partial overlap: b starts inside a if ( b . StartDate >= a . StartDate && b . StartDate < a . StartDate ) return true ; // b is fully contained by a if ( a . StartDate <= b . StartDate && a . EndDate >= b . EndDate ) return true ; // What about open-ended subscriptions? What about same-day boundaries? // What about inclusive vs exclusive end dates? ... return false ; } It looks perfectly reasonable. But start asking questions — as Steve Smith (Ardalis) does in his essay on making the implicit explicit — and you notice how much invisible knowledge this design requires. Should EndDate ever precede StartDate ? The type system doesn't say. Can a subscription have a null end date meaning it never expires? Nothing in the model communicates that. Is a subscription that ends today still active at 11:59 PM? Ask three developers and get three answers. The EndDate == default sentinel for open-ended subsc
开发者
C# 14: The `field` Keyword — Cleaner Properties, Zero Boilerplate
C# 14: The field Keyword — Cleaner Properties, Zero Boilerplate Every C# developer has been there. You start with a clean auto-property, then requirements change and you need to add a tiny bit of validation. Suddenly that one-liner explodes into six lines of boilerplate — a private backing field, a getter that just returns it, a setter that assigns it. The logic is two words. The ceremony is everything else. C# 14 fixes this with the field keyword: a contextual keyword that refers to the compiler-synthesized backing field of a property, letting you write custom accessor logic without ever declaring an explicit field. The Problem: Boilerplate Tax on Simple Properties Auto-properties are one of C#'s best quality-of-life features. This is clean: public string Username { get ; set ; } But the moment you need to trim whitespace on assignment, that cleanness evaporates: private string _username = string . Empty ; public string Username { get => _username ; set => _username = value . Trim (); } You now have six lines — and four of them exist only to hold the shape of the pattern together. The backing field _username is not carrying any meaningful design weight. Its only job is to be a storage slot that Username uses privately. You already know the compiler creates one for auto-properties. You are just forced to make it visible so you can reference it. This is the boilerplate tax. You pay it every time you add even the smallest piece of logic to a property. Why field Exists The C# language team has discussed this friction for years. The challenge was finding syntax that is: Unambiguous — no conflict with existing identifiers Familiar — consistent with how value works in setters Scoped — only meaningful inside a property accessor The solution landed in C# 14: the contextual keyword field . Just like value refers to the incoming assignment in a setter, field refers to the hidden backing storage the compiler manages for the property. It is contextual, which means it only acts