<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Denis Makarenko on Medium]]></title>
        <description><![CDATA[Stories by Denis Makarenko on Medium]]></description>
        <link>https://medium.com/@denmaklucky?source=rss-96c11f19481f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DFM-SXNnby_FNbf7yh9kdg.jpeg</url>
            <title>Stories by Denis Makarenko on Medium</title>
            <link>https://medium.com/@denmaklucky?source=rss-96c11f19481f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 21:16:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@denmaklucky/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What’s new in .NET 11]]></title>
            <link>https://medium.com/@denmaklucky/whats-new-in-net-11-545670aeaff3?source=rss-96c11f19481f------2</link>
            <guid isPermaLink="false">https://medium.com/p/545670aeaff3</guid>
            <dc:creator><![CDATA[Denis Makarenko]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 21:06:01 GMT</pubDate>
            <atom:updated>2026-10-22T21:06:01.491Z</atom:updated>
            <content:encoded><![CDATA[<h4>Explore the most interesting new features in C# 15 and .NET 11.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*96PvGkSLbNVwxZ0t7znP2A.png" /></figure><p>In a short time, a new release of .NET will be available, so let’s take a look at what new features it will include.</p><h4>Union type</h4><p>So probably the biggest update in C# 15 is union types. A union type is a set of types, and its value is a single object of one of those types. With the new release you can create and use them. Look at the following code snippet:</p><pre>public sealed record Success;<br><br>public sealed record Error;<br><br>public union Result(Success, Error);</pre><p>Now you can use it in any piece of code. For instance, a request handler will look like this:</p><pre>public sealed class CreatePostHanlder<br>{<br>    public Task&lt;Result&gt; InvokeAsync(string title)<br>    {<br>        if(string.IsNullOrEmpty(title))<br>        {<br>            return new Error();<br>        }<br><br>        return new Success();<br>    }<br>}</pre><p>Also, the switch statement no longer shows a warning about a missing default case for a union type when all cases are handled:</p><pre>app.MapPost(&quot;/posts&quot;, async (<br>  [FromServices] CreatePostHanlder handler,<br>  string title) =&gt; <br>{<br>    var result = await hanlder.InvokeAsync(title);<br><br>    return result switch<br>    {<br>        Success =&gt; TypedResults.Ok(),<br>        Error =&gt; TypedResults.BadRequest()<br>        // No warning about missing cases<br>    }<br>});</pre><p>Behind the scenes, a union type is converted to the following structure:</p><pre>[Union]<br>public struct Result : IUnion<br>{<br> [CompilerGenerated]<br> [DebuggerBrowsable(DebuggerBrowsableState.Never)]<br> private readonly object &lt;Value&gt;k__BackingField;<br><br> public object Value<br> {<br>  [IsReadOnly]<br>  [CompilerGenerated]<br>  get<br>  {<br>   return &lt;Value&gt;k__BackingField;<br>  }<br> }<br><br> [CompilerGenerated]<br> public Result([Nullable(1)] Success value)<br> {<br>  &lt;Value&gt;k__BackingField = value;<br> }<br><br> [CompilerGenerated]<br> public Result([Nullable(1)] Error value)<br> {<br>  &lt;Value&gt;k__BackingField = value;<br> }<br>}</pre><p>As you can see, a union type is just a struct with the [Union] attribute that implements the IUnion interface.</p><blockquote>You can create your own implementation without the IUnion interface. You just need to expose a Value property of type object or object?.</blockquote><p>And you can also see that all values are cast to object. This means that if you create a union type <strong>over value types</strong>, you will get boxing and unboxing under the hood.</p><p>Let’s create one using the non-boxing pattern:</p><pre>[Union]<br>public readonly struct BoolOrInt<br>{<br>    private readonly byte _kind; // 0 = empty, 1 = bool, 2 = int<br>    private readonly int _value;<br><br>    public BoolOrInt(bool value) =&gt; (_kind, _value) = (1, value ? 1 : 0);<br>    public BoolOrInt(int value) =&gt; (_kind, _value) = (2, value);<br><br>    public object? Value =&gt; _kind switch<br>    {<br>        1 =&gt; _value != 0,<br>        2 =&gt; _value,<br>        _ =&gt; null,<br>    };<br><br>    public bool HasValue =&gt; _kind != 0;<br><br>    public bool TryGetValue(out bool value)<br>    {<br>        value = _value != 0;<br>        return _kind == 1;<br>    }<br><br>    public bool TryGetValue(out int value)<br>    {<br>        value = _value;<br>        return _kind == 2;<br>    }<br>}</pre><p>To use the non-boxing pattern, your own implementation should follow these rules:</p><ul><li>A HasValue property of type bool with a public get accessor. It may optionally have an init or set accessor, which can be of any accessibility and is not used by the compiler.</li><li>A TryGetValue method for each case type. The method returns bool and takes a single out-parameter of a type that is identity-convertible to either the case type or optionally the underlying value type, if the case type is a nullable value type.</li></ul><p>Thanks to the [Union]attribute, we can create our own union type with almost any implementation. If you’re interested, check out my previous post where I created a discriminated union with a source generator and its own JSON converters.</p><p><a href="https://medium.com/@denmaklucky/union-types-no-discriminated-union-0b12b6e7de9b">Union types? No, discriminated union</a></p><h4>Closed hierarchies</h4><p>A closed hierarchy allows you to create an abstract class that can only be inherited within the assembly where you declare it. Look at the following code snippet:</p><pre>// Assembly 1<br>public closed record class Result;<br>public record class Success : Result;<br>public record class Error(string Message) : Result;<br><br>// Assembly 2<br>public record class NotFoundError : Result; // ERROR - &#39;Result&#39; is a closed class</pre><p>The switch statement also no longer shows a warning when all derived classes are handled:</p><pre>Result result = ...;<br><br>var message = state switch<br>{<br>    Success =&gt; &quot;Ok&quot;,<br>    Error error =&gt; error.Message<br>    // No warning about missing cases<br>}; </pre><p>Behind the scenes, a closed class is explicitly abstract with an additional attribute:</p><pre>[IsClosedType(DerivedTypes = new Type[]<br>{<br> typeof(Success),<br> typeof(Error)<br>})]<br>public abstract class Result : IEquatable&lt;Result&gt;<br>{<br> [CompilerFeatureRequired(&quot;ClosedClasses&quot;)]<br> [CompilerGenerated]<br> protected Result(Result original)<br> {<br> }<br><br> [CompilerFeatureRequired(&quot;ClosedClasses&quot;)]<br> protected Result()<br> {<br> }<br>}</pre><p>The Roslyn analyzer knows about all derived types thanks to the [IsClosedType] attribute.</p><h4>Extension members — indexers</h4><p>We can define indexers through extension members. For instance, IReadOnlyList&lt;T&gt; has this[int], but not this[Index]. So let’s change that:</p><pre>using System;<br>using System.Collections.Generic;<br><br>IReadOnlyList&lt;string&gt; log = [&quot;start&quot;, &quot;work&quot;, &quot;done&quot;];<br><br>Console.WriteLine(log[^1]);   // done<br>Console.WriteLine(log[^2]);   // work<br><br>public static class ReadOnlyListExtensions<br>{<br>    extension&lt;T&gt;(IReadOnlyList&lt;T&gt; list)<br>    {<br>        public T this[Index index] =&gt; list[index.GetOffset(list.Count)];<br>    }<br>}</pre><h4>Collection expression arguments</h4><p>Since C# 12, we can use collection expressions to create a collection, like below:</p><pre>List&lt;string&gt; names = [.. values];</pre><p>But it always calls the collection’s default constructor, and if there are more <strong>than 4 values</strong>, it resizes the internal buffer.</p><p>With the new syntax, we can specify the size of the collection inside the expression, like below:</p><pre>List&lt;string&gt; names = [with(capacity: 6), .. values];</pre><p>We can also specify <strong>a compare</strong>r for<strong> </strong>a set, and <strong>a custom comparer</strong> for a sorted set:</p><pre>HashSet&lt;string&gt; tags = [with(StringComparer.OrdinalIgnoreCase), &quot;Api&quot;, &quot;api&quot;, &quot;Web&quot;];<br><br>SortedSet&lt;int&gt; desc = [with(Comparer&lt;int&gt;.Create((a, b) =&gt; b.CompareTo(a))), 3, 1, 2];</pre><h4>Jump statements — labled break and continute</h4><p>You can now name an outer loop or switch statement, and exit or continue it directly from a nested loop.</p><p>So if you have two nested for loops and need to break out of the outer one, you probably had something like:</p><pre>bool found = false;<br><br>for (int x = 0; x &lt; xMax; x++)<br>{<br>    for (int y = 0; y &lt; yMax; y++)<br>    {<br>        if (grid[x, y] == target)<br>        {<br>            found = true;<br>            break;        // only exits the inner loop<br>        }<br>    }<br><br>    if (found)<br>    { <br>        break;     // need a second break for the outer loop<br>    }  <br>}</pre><p>With this labled break, you can write the following code:</p><pre>outer: for (int x = 0; x &lt; xMax; x++)<br>{<br>    for (int y = 0; y &lt; yMax; y++)<br>    {<br>        if (grid[x, y] == target)<br>        {<br>            break outer;  // exits both loops at once<br>        }<br>    }<br>}</pre><p>The label can be set directly on a for, foreach, while, do or switch.</p><h4>System.Text.Json</h4><p>System.Text.Json can now serialize and deserialize IReadOnlySet&lt;T&gt;. Before, only ISet&lt;T&gt; and concrete types like HashSet&lt;T&gt; worked, and when we try to serialize and deserialize IReadOnlySet&lt;T&gt; it throws NotSupportedException.</p><pre>IReadOnlySet&lt;string&gt; names = new HashSet&lt;string&gt; { &quot;denis&quot;, &quot;dan&quot; };<br><br>string json = JsonSerializer.Serialize(names);<br>var back = JsonSerializer.Deserialize&lt;IReadOnlySet&lt;string&gt;&gt;(json); // works now</pre><p>Now System.Text.Json support serialize of IAsyncEnumerable&lt;T&gt;. Look at the following code snippet:</p><pre>static async IAsyncEnumerable&lt;Name&gt; GetNames()<br>{<br>    yield return new(&quot;denis&quot;);<br>    yield return new(&quot;dan&quot;);<br>}<br><br>await JsonSerializer.SerializeAsyncEnumerable(stream, GetReadings(), topLevelValues: true);<br><br>public sealed record Name(string Value);</pre><p>Also, System.Text.Json can serialize and deserialize union types. Look at our example again:</p><pre>public sealed record Succes(int Id);<br><br>public sealed record Error(string Message);<br><br>public union Result(Succes, Error);</pre><p>Serialization works out of the box, but to be able to deserialize, we have to specify TypeClassifier either on the union type or globally in JsonSerializerOptions:</p><pre>[JsonUnion(TypeClassifier = typeof(ResultClassifier))]<br>public union Result(Succes, Error);<br><br>// or in options<br><br>var jsonSerializerOptions = new JsonSerializerOptions<br>{<br>    TypeClassifiers = { new ResultClassifier() }<br>};</pre><p>The type classifier should implement JsonTypeClassifierFactory&lt;TUnion&gt; :</p><pre>public sealed class ResultClassifier : JsonTypeClassifierFactory&lt;Result&gt;<br>{<br>    public override JsonTypeClassifier CreateJsonClassifier(<br>      JsonTypeClassifierContext context,<br>      JsonSerializerOptions options)<br>    {<br>        return static (ref Utf8JsonReader reader) =&gt;<br>        {<br>            if (reader.TokenType is not JsonTokenType.StartObject)<br>            {<br>              return null;<br>            }<br><br>            while (reader.Read() &amp;&amp; reader.TokenType is not JsonTokenType.EndObject)<br>            {<br>                if (reader.ValueTextEquals(&quot;Id&quot;u8))<br>                {<br>                  return typeof(Succes);<br>                }<br>  <br>                if (reader.ValueTextEquals(&quot;Message&quot;u8))<br>                {<br>                  return typeof(Error);<br>                }<br><br>                reader.Read();<br>                reader.Skip();<br>            }<br><br>            return null;<br>        };<br>    }<br>}</pre><h4>Asynchronous validation with DataAnnotations</h4><p>To use asynchronous validation, we need to implement a new validation attribute that derives from AsyncValidationAttribute. For instance, let’s say we want to have a unique username. For that, we need to implement UniqueUsernameAttribute as below:</p><pre>[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)]<br>public sealed class UniqueUsernameAttribute : AsyncValidationAttribute<br>{<br>    protected override ValidationResult? IsValid(object? value,<br>      ValidationContext validationContext) =&gt;<br>        throw new InvalidOperationException($&quot;Validate the attribute with {nameof(IsValidAsync)}.&quot;);<br><br>    protected override async Task&lt;ValidationResult?&gt; IsValidAsync(object? value,<br>      ValidationContext validationContext,<br>      CancellationToken cancellationToken)<br>    {<br>        var userService = validationContext.GetRequiredService&lt;IUserService&gt;();<br><br>        if (value is string username &amp;&amp;<br>            await userService.ExistAsync(username))<br>        {<br>            return new ValidationResult($&quot;User with `{username}` already exists.&quot;);<br>        }<br><br>        return ValidationResult.Success;<br>    }<br>}</pre><p>As you can see, it exposes two required methods: IsValid and IsValidAsync.</p><p>And semantically, the synchronous variant of the validation shouldn’t be here. If you’re wondering why we have a synchronous validation method here anyway, it’s because AsyncValidationAttribute is a descendant of the well-known ValidationAttribute.</p><p>So the inheritance looks like this:</p><pre>Object --&gt; Attribute --&gt; ValidationAttribute --&gt; AsyncValidationAttribute</pre><p>Anyway, to use it, we just need to add the newly created attribute to the property in our model, something like this:</p><pre>// attribute over the UserName<br>public sealed record RegisterUserRequest([UniqueUsername] string Username);</pre><p>Also, if you use Minimal APIs, don’t forget to turn on validation by adding the following line:</p><pre>using AsyncValidation;<br>using Microsoft.AspNetCore.Mvc;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services.AddValidation();// &lt;-- added a new line here<br><br>var app = builder.Build();<br><br>// ednpoints<br><br>app.Run();</pre><h4>File-based apps</h4><p>Now file-based apps can reference another file-based app with a new directive.</p><pre>#:ref lib.cs //&lt;-- link to the file-based app<br><br>using Extensions;<br><br>var name = &quot;Denis&quot;;<br><br>Console.WriteLine(name.IsEmpty);</pre><p>We can also reference a DLL with the following directive:</p><pre>#:include ./libs/lib.dll<br><br>using Extensions;<br><br>var name = &quot;Denis&quot;;<br><br>Console.WriteLine(name.IsEmpty);</pre><p>dotnet ef supports file-based apps, so migration and scaffolding commands can work with the single-file app model:</p><pre>dotnet ef migrations add InitialCreate --file .\App.cs</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=545670aeaff3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Updates in System.Text.Json you shouldn’t skip]]></title>
            <link>https://medium.com/@denmaklucky/updates-in-system-text-json-you-shouldnt-skip-1798c0139018?source=rss-96c11f19481f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1798c0139018</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Denis Makarenko]]></dc:creator>
            <pubDate>Sat, 10 Oct 2026 14:13:13 GMT</pubDate>
            <atom:updated>2026-10-10T14:13:13.282Z</atom:updated>
            <content:encoded><![CDATA[<h4>System.Text.Json can now serialize and deserialize the new C# union types.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*wbN_6jL5Cjw-_f81h7kC_g.png" /></figure><p>When new union types came out, they had one big problem: JSON deserialization didn’t work with them.</p><p>That’s why, in one of my previous posts, I suggested adding serialization/deserialization support with a source generator. This approach avoids that limitation of union types.</p><p>If you’re interested, feel free to check out that post.</p><p><a href="https://medium.com/@denmaklucky/union-types-no-discriminated-union-0b12b6e7de9b">Union types? No, discriminated union</a></p><p>However, with the latest update to System.Text.Json, we can now deserialize union types right out of the box.</p><p>With the new API, we can specify a <strong>type classifier</strong> that guides the JsonSerializer when it deals with union types.</p><p>To show how it works, let’s say we have a union type Result like below:</p><pre>public sealed record Succes(int Id);<br><br>public sealed record Error(string Message);<br><br>public union Result(Succes, Error);</pre><p>Here, the Result union has two possible cases: Success with the Id of resource, and Error with a Message for the error description.</p><p>To give JsonSerializer a hint, we need to add the new [JsonUnion] attribute to our union type.</p><pre>[JsonUnion]<br>public union Result(Succes, Error);</pre><p>Next, we have to specify our <strong>classifier</strong>, but first we need to create it.</p><p>For that, we create a new class that implements JsonTypeClassifierFactory&lt;TUnion&gt;, where <em>TUnion</em> is our union type.</p><p>So let’s create a ResultClassifier, which implementation is shown below:</p><pre>public sealed class ResultClassifier : JsonTypeClassifierFactory&lt;Result&gt;<br>{<br>    public override JsonTypeClassifier CreateJsonClassifier(<br>      JsonTypeClassifierContext context,<br>      JsonSerializerOptions options)<br>    {<br>        return static (ref Utf8JsonReader reader) =&gt;<br>        {<br>            if (reader.TokenType is not JsonTokenType.StartObject)<br>            {<br>              return null;<br>            }<br><br>            while (reader.Read() &amp;&amp; reader.TokenType is not JsonTokenType.EndObject)<br>            {<br>                if (reader.ValueTextEquals(&quot;Id&quot;u8))<br>                {<br>                  return typeof(Succes);<br>                }<br>  <br>                if (reader.ValueTextEquals(&quot;Message&quot;u8))<br>                {<br>                  return typeof(Error);<br>                }<br><br>                reader.Read();<br>                reader.Skip();<br>            }<br><br>            return null;<br>        };<br>    }<br>}</pre><p>In the ResultClassifier, we just look for a <strong>type-specific property</strong>. Once we find it, we know this property belongs only to <strong>one specific type</strong>, so we return that type.</p><p>But sometimes we need to work with the entire object. For that, we can change our ResultClassifier to parse the JSON into a JsonObject and work with it:</p><pre>public sealed class ResultClassifier : JsonTypeClassifierFactory&lt;Result&gt;<br>{<br>    public override JsonTypeClassifier CreateJsonClassifier(<br>        JsonTypeClassifierContext context, JsonSerializerOptions options)<br>    {<br>        return static (ref Utf8JsonReader reader) =&gt;<br>        {<br>            if (JsonNode.Parse(ref reader) is JsonObject obj)<br>            {<br>                if (obj.ContainsKey(&quot;Id&quot;))<br>                {<br>                    return typeof(Succes);<br>                }<br><br>                if (obj.ContainsKey(&quot;Message&quot;))<br>                {<br>                    return typeof(Error);<br>                }<br>            }<br><br>            return null;<br>        };<br>    }<br>}</pre><p>It’s much easier to maintain, but it also brings the allocation cost of the object.</p><p>To use our type classifier, let’s adjust the [JsonUnion] attribute by specifying the ResultClassifier type:</p><pre>[JsonUnion(TypeClassifier = typeof(ResultClassifier))]<br>public union Result(Succes, Error);</pre><p>If you want to specify the type classifier globally, you can set it in the <strong>options</strong>, like this:</p><pre>var jsonSerializerOptions = new JsonSerializerOptions<br>{<br>    TypeClassifiers = { new ResultClassifier() }<br>};</pre><p>It’s also good to know that, by default, JsonSerializer can automatically handle union types with different primitive types, like bool and string, string and number, and so on.</p><p>For instance, let’s say we have a Result union type that contains a bool indicating success and a string indicating an error.</p><p>For this union type, we don’t need to write a type classifier, and deserialization works out of the box:</p><pre>union Result(bool, string);<br><br>Result originalResult = true;<br><br>var jsonSuccess = JsonSerializer.Serialize(originalResult);<br><br>Console.WriteLine(jsonSuccess);// will be just &quot;true&quot; in Colsole<br><br>var result = JsonSerializer.Deserialize&lt;Result&gt;(jsonSuccess);// all good here</pre><p>If you’re wondering why there’s no default type classifier for all union types in an assembly, it’s because only the developer knows exactly how to map the JSON to different types.</p><p>It’s also good to know the difference between a type classifier and a JSON converter. A JSON converter has to handle both serialization and deserialization. On the other hand, a type classifier doesn’t take part in serialization or deserialization at all. It only determines the type from the JSON.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1798c0139018" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[File-based apps can reference other C# files]]></title>
            <link>https://medium.com/@denmaklucky/file-based-apps-can-reference-other-c-files-65ffa06f7894?source=rss-96c11f19481f------2</link>
            <guid isPermaLink="false">https://medium.com/p/65ffa06f7894</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Denis Makarenko]]></dc:creator>
            <pubDate>Mon, 05 Oct 2026 00:21:01 GMT</pubDate>
            <atom:updated>2026-10-05T00:21:01.601Z</atom:updated>
            <content:encoded><![CDATA[<h4>File-based apps can now split code across files without first creating a project.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*HPv_oEhz6yEHT-pAdLvg0g.png" /></figure><p>Since .NET 10, we have the possibility to create <strong>a file-based app without creating a project and solution</strong>.</p><p>It’s very convenient when you need to check or create something in C# without dealing with the extra stuff.</p><p>Personally, I use this to check how some code behaves under certain conditions. For instance, to prove a concept in C# code or to check how JSON conversion works with union types. I just create a file and put everything I need there and nothing else.</p><p>It can also be used for creating a mini app, script, etc. However, the point of a C# file-based app was that all the logic should be inside <strong>one file</strong>.</p><p>Since now you can split the logic into separated files or use an already created C# files in your file-based app.</p><p>To illustrate what I mean, let’s create a new library file that will contain an extension:</p><pre>namespace Extensions;<br><br>public static class StringExtensions<br>{<br>    extension(string str)<br>    {<br>        public bool IsEmpty =&gt; string.IsNullOrEmpty(str);<br>    }<br>}</pre><p>And now let’s create a new file-based app that will reference it:</p><pre>#:ref lib.cs<br>// it&#39;s temporary, cause I&#39;m using .NET11 rc-1<br>#:property ExperimentalFileBasedProgramEnableRefDirective=true <br><br>using Extensions;<br><br>var name = &quot;Denis&quot;;<br><br>Console.WriteLine(name.IsEmpty);</pre><p>However, when we try to build the file-based app, we will see an error.</p><pre>CSC : error CS5001: Program does not contain a static &#39;Main&#39; method suitable for an entry point<br>The build failed. Fix the build errors and run again.</pre><p>I believe it’s because this feature is still in preview, and to resolve it, we need to add the following line to our extensions library file:</p><pre>// add this line<br>#:property OutputType=Library<br><br>namespace Extensions;<br><br>public static class StringExtensions<br>{<br>    extension(string str)<br>    {<br>        public bool IsEmpty =&gt; string.IsNullOrEmpty(str);<br>    }<br>}</pre><p>Now we will see in the console that the reference is working as expected and display the false .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65ffa06f7894" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Closed class hierachies in C#/.NET]]></title>
            <link>https://medium.com/@denmaklucky/closed-class-hierachies-in-c-net-835a0b1b348a?source=rss-96c11f19481f------2</link>
            <guid isPermaLink="false">https://medium.com/p/835a0b1b348a</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Denis Makarenko]]></dc:creator>
            <pubDate>Thu, 01 Oct 2026 22:41:01 GMT</pubDate>
            <atom:updated>2026-10-01T22:41:01.644Z</atom:updated>
            <content:encoded><![CDATA[<h4>Now we can create an abstract class which will be available only for the current assembly.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*2_PF_fFK4fsEZgz9s-CmTg.png" /></figure><p>Before this feature, we actually didn’t have anything like this that would allow us to create <strong>a closed class</strong>; however, we could easily simulate it with <strong>nested classes</strong>.</p><p>To see what I’m talking about, look at the following example:</p><pre>public abstract class HandlerResult<br>{<br>    private HandlerResult()<br>    {<br>    }<br><br>    public sealed class Success : HandlerResult;<br><br>    public sealed class Failed : HandlerResult;<br>}</pre><p>With the new release, we have a new keyword — closed, which allows us to create <strong>closed class hierarchies</strong>, where subtypes must be declared in the same assembly as the closed base class.</p><p>Now we can easily have something like this:</p><pre>public closed class CommandResult;<br><br>public sealed class Success : CommandResult;<br><br>public sealed class Failed : CommandResult;</pre><p>Want to understand how this feature works? Let’s look under the hood to see the lowered C# that these closed classes are converted into.</p><p>For that, I’m going to use <a href="https://lab.razor.fyi/">this tool</a> and here is a complited low C# code:</p><pre>[IsClosedType(DerivedTypes = new Type[]<br>{<br> typeof(Success),<br> typeof(Failed)<br>})]<br>public abstract class CommandResult<br>{<br> [CompilerFeatureRequired(&quot;ClosedClasses&quot;)]<br> protected CommandResult()<br> {<br> }<br>}<br><br>public sealed class Success : CommandResult<br>{<br>}<br><br>public sealed class Failed : CommandResult<br>{<br>}</pre><p>The closed keyword converts the class into an abstract one, along with an attribute that marks it as a closed type. This attribute helps us in the switch case.</p><p>Basically, now we can use a switch statement without a default case and without a warning, because thanks to the attribute, the switch knows exactly which subtypes the closed type has.</p><p>To illustrate what I’m talking about, see the picture below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*elYGtWf-qUaYXQ15tdtRYw.png" /></figure><p>If we go back to our example with the nested classes, we will see that the IDE shows us a warning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*vyQ_l9OJU3fkAMiOODUSiA.png" /></figure><p>The warning message is:</p><blockquote>The ‘switch’ expression does not handle all possible inputs (it is not exhaustive). For example, the pattern ‘_’ is not covered</blockquote><blockquote>🤝 Let’s connect on LinkedIn!<br>If you enjoyed this post or want to chat more about it, feel free to connect with me on <a href="https://www.linkedin.com/in/denmaklucky/">LinkedIn</a>. I’d love to hear your thoughts and keep in touch!</blockquote><p>So now we have another way to clean up our hierarchies with the new closed class.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=835a0b1b348a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Validation improvements in ASP.NET Core]]></title>
            <link>https://medium.com/@denmaklucky/validation-improvements-in-asp-net-core-bb078c93b7b9?source=rss-96c11f19481f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb078c93b7b9</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Denis Makarenko]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 23:01:02 GMT</pubDate>
            <atom:updated>2026-09-16T07:46:51.313Z</atom:updated>
            <content:encoded><![CDATA[<h4>The validation pipeline is now asynchronous, so you can inject dependencies and await DB calls directly in a validation attribute.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*2-A1wPam8ZZrQeAvMJuTWQ.png" /></figure><p>With the brand new AsyncValidationAttribute, we can now validate a model asynchronously.</p><p>To illustrate this, let’s create an endpoint that allows registering an user, but with <strong>unique usernames</strong> only.</p><p>First of all, let’s create a dummy service and name it IUserService:</p><pre>public interface IUserService<br>{<br>    Task&lt;bool&gt; ExistAsync(string username);<br><br>    Task RegisterAsync(string username);<br>}<br><br>public sealed class UserService : IUserService<br>{<br>    // it&#39;s our simulation of db<br>    private static readonly List&lt;string&gt; _usernames = [];<br><br>    public async Task&lt;bool&gt; ExistAsync(string username)<br>    {<br>        var isExisting = _usernames.Contains(username);<br><br>        await Task.Delay(1_000);<br><br>        return isExisting;<br>    }<br><br>    public async Task RegisterAsync(string username)<br>    {<br>        var isExisting = await ExistAsync(username);<br><br>        if (isExisting)<br>        {<br>            throw new InvalidOperationException(&quot;Could not register an user.&quot;);<br>        }<br><br>        _usernames.Add(username);<br>    }<br>}</pre><p>As you can see, the service has only two methods: ExistsAsync and RegisterAsync. They are only needed to demonstrate how we can use an <strong>async method inside a validation attribute</strong>.</p><p>The next step is to register our service in DI. For that, I’ll add the following line in the Program.cs file:</p><pre>var builder = WebApplication.CreateBuilder(args);<br><br>// register a service<br>builder.Services.AddSingleton&lt;IUserService, UserService&gt;();<br><br>var app = builder.Build();<br><br>app.Run();</pre><p>After that, let’s create the new attribute itself.</p><p>I’ll create the UniqueUsernameAttribute, and it will inherit from AsyncValidationAttribute:</p><pre>[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)]<br>public sealed class UniqueUsernameAttribute : AsyncValidationAttribute<br>{<br>    protected override ValidationResult? IsValid(object? value,<br>      ValidationContext validationContext) =&gt;<br>        throw new InvalidOperationException($&quot;Validate the attribute with {nameof(IsValidAsync)}.&quot;);<br><br>    protected override async Task&lt;ValidationResult?&gt; IsValidAsync(object? value,<br>      ValidationContext validationContext,<br>      CancellationToken cancellationToken)<br>    {<br>        var userService = validationContext.GetRequiredService&lt;IUserService&gt;();<br><br>        if (value is string username &amp;&amp;<br>            await userService.ExistAsync(username))<br>        {<br>            return new ValidationResult($&quot;User with `{username}` already exists.&quot;);<br>        }<br><br>        return ValidationResult.Success;<br>    }<br>}</pre><p>As you can see, it exposes two required methods: IsValid and IsValidAsync.</p><p>And semantically, the synchronous variant of the validation shouldn’t be here. If you’re wondering why we have a synchronous validation method here anyway, it’s because AsyncValidationAttribute is a descendant of the well-known ValidationAttribute.</p><p>So the inheritance looks like this:</p><pre>Object --&gt; Attribute --&gt; ValidationAttribute --&gt; AsyncValidationAttribute</pre><p>I can guess this happened because redoing the whole validation flow for the new attribute would have been a massive amount of work, so the .NET team decided to just extend the existing flow by introducing a new attribute. <strong>And this means that all async attributes will have an unnecessary synchronous validation method</strong>.</p><p>Anyway, the next step is to create a new endpoint and a new request class, which will represent the registration request, and to apply the unique username attribute to the name property of this class.</p><pre>public sealed record RegisterUserRequest([UniqueUsername] string Username);</pre><p>The endpoint logic here:</p><pre>app.MapPost(&quot;/users&quot;, async ([FromServices] IUserService service, RegisterUserRequest request) =&gt;<br>{<br>    await service.RegisterAsync(request.Username);<br><br>    return TypedResults.Ok();<br>});</pre><p>And now, if we run the app and invoke the endpoint above with the same username twice, we’ll see an error — but not the one we would expect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*8lTTSQzyhea9iwGeer3h3Q.png" /></figure><p>This happened because I forgot to enable validation on our endpoints, so that they use the data annotation attributes to validate our request.</p><p>It can be done by adding AddValidation(), and after that, our Program.cs is going to look like this:</p><pre>using AsyncValidation;<br>using Microsoft.AspNetCore.Mvc;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services.AddSingleton&lt;IUserService, UserService&gt;();<br><br>builder.Services.AddValidation();// &lt;-- added a new line here<br><br>var app = builder.Build();<br><br>app.MapPost(&quot;/users&quot;, async ([FromServices] IUserService service, RegisterUserRequest request) =&gt;<br>{<br>    await service.RegisterAsync(request.Username);<br><br>    return TypedResults.Ok();<br>});<br><br>app.Run();</pre><p>And now let’s try again and see how our new endpoint handles it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XZr668gL2KDaIV5eBVNdJg.gif" /></figure><blockquote>🤝 Let’s connect on LinkedIn!<br>If you enjoyed this post or want to chat more about it, feel free to connect with me on <a href="https://www.linkedin.com/in/denmaklucky/">LinkedIn</a>. I’d love to hear your thoughts and keep in touch!</blockquote><p>So now we have a legitimate way to add async validation through an attribute. And it can be any kind of validation: against a database, against Redis or another cache. You could even use it as an idempotency mechanism for your own needs.</p><p>This small change opens up a new way to validate our requests.</p><p>As always, here’s the <a href="https://github.com/denmaklucky/medium/tree/master/src/2026/ValidationImprovements">link </a>to the repository for you to explore.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb078c93b7b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use Alpine.js and htmx with ASP.NET Core]]></title>
            <link>https://medium.com/@denmaklucky/use-alpine-js-and-htmx-with-asp-net-core-ea34911a0a47?source=rss-96c11f19481f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea34911a0a47</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Denis Makarenko]]></dc:creator>
            <pubDate>Sun, 06 Sep 2026 23:06:00 GMT</pubDate>
            <atom:updated>2026-09-06T23:06:00.848Z</atom:updated>
            <content:encoded><![CDATA[<h4>For years, ASP.NET has struggled with the absence of normal interactivity. But with these two tiny libraries, it seems that can change.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*YTJt9_Wm7JE0ok327PUtGQ.png" /></figure><h4>Abstract</h4><p>ASP.NET web apps (Razor Pages and MVC) are really powerful. Static rendering, routing, UI class libraries — all of it is so easy to use.</p><p>But it also struggles with interactivity. And usually devs solve that with plain js or jQuery.</p><p>Seems like this could finally change, thanks to two libraries: <a href="https://htmx.org/"><strong>htmx </strong></a>and <a href="https://alpinejs.dev/"><strong>Alpine.js</strong></a>.</p><p>htmx is the library that takes care of making AJAX requests and swapping parts of the HTML in a seamless way.</p><p>Alpine.js is a small library that basically brings interactivity to the client in a modern way.</p><p>Combine them together and you get a server-rendered app where the server handles caching, routing and rendering — but it feels like a real SPA, with almost all the interactivity you’ll ever need. And the important part: <strong>without tons of client code.</strong></p><p>So in this post I want to show what this setup is capable of through use cases will need for the app. My tech stack will be Razor Pages (though everything applies to ASP.NET Core MVC too), Alpine.js, htmx, and Bulma CSS.</p><h4>Bulk actions in a table</h4><p>A table with items, where users can select a few of them and run a bulk operation — it’s a really common way to work with data.</p><p>The table will hold Product entities. The entity with a few properties, just to have something to show:</p><pre>public enum State<br>{<br>  Active,<br>  Archived,<br>  Deleted<br>}<br><br>public sealed class Product<br>{<br>  public int Id { get; set; }<br><br>  public string Name { get; set; } = string.Empty;<br><br>  public State State { get; set; }<br>}</pre><p>On the page, products will be represented as a table:</p><pre>&lt;table class=&quot;table is-fullwidth is-striped is-hoverable&quot;&gt;<br>    &lt;thead&gt;<br>        &lt;tr&gt;<br>            &lt;th&gt;<br>                &lt;input type=&quot;checkbox&quot; /&gt;<br>            &lt;/th&gt;<br>            &lt;th&gt;Id&lt;/th&gt;<br>            &lt;th&gt;Name&lt;/th&gt;<br>            &lt;th&gt;Status&lt;/th&gt;<br>        &lt;/tr&gt;<br>    &lt;/thead&gt;<br>    &lt;tbody&gt;<br>        @foreach (var product in Model)<br>        {<br>            &lt;tr&gt;<br>                &lt;td&gt;<br>                    &lt;input type=&quot;checkbox&quot; name=&quot;ids&quot; value=&quot;@product.Id&quot; /&gt;<br>                &lt;/td&gt;<br>                &lt;td&gt;@product.Id&lt;/td&gt;<br>                &lt;td&gt;@product.Name&lt;/td&gt;<br>                &lt;td&gt;<br>                    &lt;span class=&quot;tag @(product.State switch<br>                                      {<br>                                         State.Deleted =&gt; &quot;is-danger&quot;,<br>                                         State.Archived =&gt; &quot;is-warning&quot;,<br>                                         _ =&gt; &quot;is-light&quot;<br>                                       })&quot;&gt;@product.State&lt;/span&gt;<br>                &lt;/td&gt;<br>            &lt;/tr&gt;<br>        }<br>    &lt;/tbody&gt;<br>&lt;/table&gt;</pre><p>The real magic of communicating with the server via htmx happens right here:</p><pre>&lt;button type=&quot;button&quot;<br>        class=&quot;button is-danger&quot;<br>        hx-delete=&quot;@Url.Page(&quot;BulkActions&quot;, &quot;Delete&quot;)&quot;<br>        hx-include=&quot;#products [name=&#39;ids&#39;]&quot;<br>        hx-target=&quot;#products&quot;<br>        hx-swap=&quot;outerHTML&quot;&gt;<br>    Delete (&lt;span x-text=&quot;selectedCount&quot;&gt;&lt;/span&gt;)<br>&lt;/button&gt;</pre><ul><li>hx-delete — makes an AJAX DELETE request to Url.Page(“BulkActions”, “Delete”)</li><li>hx-include — basically a selector, which includes in the request all inputs with the name ids</li><li>hx-target — the target of our replacement with the HTML from the server (#products is a div with the whole table)</li><li>hx-swap — tells htmx exactly how the replacement should happen</li></ul><p>It could be hard to read the syntax at the first time, but once you get used to it, it won’t be hard anymore.</p><p>The page handler that will be called by the button Delete:</p><pre>public PartialViewResult OnDelete(int[] ids)<br>{<br>  foreach (var product in Store.Where(p =&gt; ids.Contains(p.Id)))<br>  {<br>    product.State = State.Deleted;<br>  }<br><br>  return Partial(&quot;_ProductsTable&quot;, Store);<br>}</pre><p>But we don’t want to show the buttons when no item is selected — and here we’ll use Alpine.js.</p><p>So we’re going to create a JavaScript object that serves as the model for our partial view:</p><pre>@{<br>    var items = string.Join(&quot;, &quot;, Model.Select(p =&gt; $&quot;{{ id: {p.Id}, selected: false }}&quot;));<br>}<br><br>&lt;div id=&quot;products&quot;<br>     x-data=&quot;{<br>         items: [@Html.Raw(items)],<br>         item(id) { return this.items.find(i =&gt; i.id === id) },<br>         get selectedCount() { return this.items.filter(i =&gt; i.selected).length }<br>     }&quot;&gt;<br>&lt;/div&gt;</pre><ul><li>x-data — the Alpine.js attribute that provides something like a view model for the view</li></ul><p>The JavaScript object contains the following members:</p><ul><li>items — the items that will be represented in the table; has two property id and selected</li><li>item(id) — a method that returns a specific item by id</li><li>selectedCount — returns the number of selected items</li></ul><p>I’ve also adjusted the table code I showed earlier, to something like this:</p><pre>&lt;tr x-bind:class=&quot;{ &#39;is-selected&#39;: item(@product.Id).selected }&quot;&gt;<br>    &lt;td&gt;<br>        &lt;input type=&quot;checkbox&quot; name=&quot;ids&quot; value=&quot;@product.Id&quot; x-model=&quot;item(@product.Id).selected&quot; /&gt;<br>    &lt;/td&gt;<br>    &lt;td&gt;@product.Id&lt;/td&gt;<br>    &lt;td&gt;@product.Name&lt;/td&gt;<br>    &lt;td&gt;<br>        &lt;span class=&quot;tag @(product.State switch<br>                          {<br>                              State.Deleted =&gt; &quot;is-danger&quot;,<br>                              State.Archived =&gt; &quot;is-warning&quot;,<br>                              _ =&gt; &quot;is-light&quot;<br>                          })&quot;&gt;@product.State&lt;/span&gt;<br>    &lt;/td&gt;<br>&lt;/tr&gt;</pre><p>The adjustment does the following: if an item is selected, the is-selected class is applied.</p><p>And that’s it. You basically get a table with bulk actions in just a few lines of code.</p><p>Let’s see how it looks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-5Lc37fumyhCv4gOZEswYw.gif" /></figure><h4>Context menu</h4><p>Another common need is having <strong>a context menu on an item</strong>. To illustrate the context menu, I’m going to use the table.</p><p>The table’s row will hold Product entity:</p><pre>public enum State<br>{<br>  Active,<br>  Archived,<br>  Deleted<br>}<br><br>public sealed class Product<br>{<br>  public int Id { get; set; }<br><br>  public string Name { get; set; } = string.Empty;<br><br>  public State State { get; set; }<br>}</pre><p>Each product entity will be in a row tr, with actions that show up when the user clicks on the three dots:</p><pre>&lt;tr&gt;<br>    &lt;td&gt;@product.Id&lt;/td&gt;<br>    &lt;td&gt;@product.Name&lt;/td&gt;<br>    &lt;td&gt;<br>        &lt;span class=&quot;tag @(product.State switch<br>                         {<br>                             State.Deleted =&gt; &quot;is-danger&quot;,<br>                             State.Archived =&gt; &quot;is-warning&quot;,<br>                             _ =&gt; &quot;is-light&quot;<br>                         })&quot;&gt;@product.State&lt;/span&gt;<br>    &lt;/td&gt;<br>    &lt;td class=&quot;has-text-right&quot;&gt;<br>        &lt;div class=&quot;dropdown is-right&quot;<br>             x-data=&quot;{ open: false }&quot;<br>             x-bind:class=&quot;{ &#39;is-active&#39;: open }&quot;<br>             x-on:click.outside=&quot;open = false&quot;&gt;<br>            &lt;div class=&quot;dropdown-trigger&quot;&gt;<br>                &lt;button type=&quot;button&quot;<br>                        class=&quot;button is-white&quot;<br>                        aria-haspopup=&quot;true&quot;<br>                        aria-label=&quot;Actions&quot;<br>                        x-on:click=&quot;open = !open&quot;&gt;<br>                    &amp;#8942; @* it&#39;s three dots *@<br>                &lt;/button&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;dropdown-menu&quot; role=&quot;menu&quot;&gt;<br>                &lt;div class=&quot;dropdown-content&quot;&gt;<br>                    &lt;a class=&quot;dropdown-item has-text-danger&quot;<br>                       hx-delete=&quot;@Url.Page(&quot;ContextMenu&quot;, new { id = product.Id })&quot;<br>                       hx-target=&quot;#products&quot;<br>                       hx-swap=&quot;outerHTML&quot;&gt;<br>                        Delete<br>                    &lt;/a&gt;<br>                    &lt;a class=&quot;dropdown-item&quot;<br>                       hx-post=&quot;@Url.Page(&quot;ContextMenu&quot;, &quot;Archive&quot;, new { id = product.Id })&quot;<br>                       hx-target=&quot;#products&quot;<br>                       hx-swap=&quot;outerHTML&quot;&gt;<br>                        Archive<br>                    &lt;/a&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/td&gt;<br>&lt;/tr&gt;</pre><p>As you can see, toggling visibility on user click can be done with Alpine.js, and the view model of row is basically one property — open. Based on that property, we can easily control opening and closing of our context menu.</p><p>You can also see that instead of using hx-include, we just specify the id inside the URL of the action button:</p><pre>hx-delete=&quot;@Url.Page(&quot;ContextMenu&quot;, new { id = product.Id })&quot; @* pass id *@</pre><p>On the page, we try to find a product entity based on the provided id and “delete” it:</p><pre>public PartialViewResult OnDelete(int id)<br>{<br>    SetState(id, State.Deleted);<br><br>    return Partial(&quot;_ContextMenuTable&quot;, Store);<br>}<br><br>private static void SetState(int id, State state)<br>{<br>    var product = Store.FirstOrDefault(p =&gt; p.Id == id);<br><br>    if (product is not null)<br>    {<br>        product.State = state;<br>    }<br>}</pre><p>And here’s what we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c3FztaogClqzy57eNc9rDg.gif" /></figure><h4>Dialog</h4><p>A dialog is another way to interact with the user, and it can be used in different ways.</p><p>Showing a dialog can be done with pure htmx, but what if you need to add interactivity to the dialog itself? That’s where Alpine.js comes in.</p><p>To show the dialog, I’ll have a simple button that makes a request to the server and swap recieved HTML with #dialog :</p><pre>@*html code*@<br><br>&lt;div class=&quot;has-text-centered&quot;&gt;<br>    &lt;button type=&quot;button&quot;<br>            class=&quot;button is-primary&quot;<br>            hx-get=&quot;@Url.Page(&quot;Dialog&quot;, &quot;Dialog&quot;)&quot;<br>            hx-target=&quot;#dialog&quot;<br>            hx-swap=&quot;innerHTML&quot;&gt;<br>        Open dialog<br>    &lt;/button&gt;<br>&lt;/div&gt;<br><br>&lt;div id=&quot;dialog&quot;&gt;&lt;/div&gt;<br><br>// page&#39;s handler<br><br>public PartialViewResult OnGetDialog()<br>{<br>  return Partial(&quot;_Dialog&quot;, Store);<br>}</pre><p>I want to give the dialog the ability to expand by some percentage of the page.</p><p>For that, I’ll create a JavaScript object inside the x-data attribute:</p><pre>{<br>    ratio: 0.5,<br>    viewportWidth: window.innerWidth,<br>    viewportHeight: window.innerHeight,<br>    get width() { return this.viewportWidth * this.ratio },<br>    get height() { return this.viewportHeight * this.ratio }<br>}</pre><p>When dialog is open in first time the ratio of it will be <strong>0.5</strong>, but when user click on extand button I will change the ration to <strong>0.8</strong>:</p><pre>&lt;button type=&quot;button&quot;<br>        class=&quot;button is-light&quot;<br>        x-on:click=&quot;ratio = ratio === 0.5 ? 0.8 : 0.5&quot;<br>        x-text=&quot;ratio === 0.5 ? &#39;Expand to 80%&#39; : &#39;Shrink to 50%&#39;&quot;&gt;</pre><p>And here what we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lUKNfAWa3Yq31tVgLhHiLg.gif" /></figure><h4>Block empty requests</h4><p>Blocking unnecessary requests is another thing where the combination of htmx and Alpine.js can be really useful.</p><p>To illustrate how we can implement this, let me create a table with a filter, where the filter can only <strong>be applied after it has been changed</strong>. So no empty requests can be made until the user makes some changes.</p><p>I’ll have a button that makes a request to the page handler with the provided filter and swaps #products with the received HTML:</p><pre>&lt;button type=&quot;button&quot;<br>        class=&quot;button is-primary&quot;<br>        hx-get=&quot;@Url.Page(&quot;SelectFilter&quot;, &quot;Filter&quot;)&quot;<br>        hx-include=&quot;[name=&#39;state&#39;]&quot;<br>        hx-target=&quot;#products&quot;<br>        hx-swap=&quot;outerHTML&quot;&gt;<br>     Search<br>&lt;/button&gt;</pre><p>But without Alpine.js it will work without any protection, so let’s add a disabled state once the user has already clicked the filter:</p><pre>&lt;button type=&quot;button&quot;<br>        class=&quot;button is-primary&quot;<br>        x-bind:disabled=&quot;selected === applied&quot; @* disable after request*@<br>        x-on:htmx:after-request=&quot;applied = selected&quot;<br>        hx-get=&quot;@Url.Page(&quot;SelectFilter&quot;, &quot;Filter&quot;)&quot;<br>        hx-include=&quot;[name=&#39;state&#39;]&quot;<br>        hx-target=&quot;#products&quot;<br>        hx-swap=&quot;outerHTML&quot;&gt;<br>    Search<br>&lt;/button&gt;</pre><p>Here is an interesting line of code:</p><pre>x-on:htmx:after-request=&quot;applied = selected&quot;</pre><p>Basically, we can also subscribe to htmx events, not just common JavaScript events, and that gives us a pretty powerful mechanism for <strong>updating our UI</strong>.</p><p>And here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*joOQmSXMtBPb6jNdkvOSdg.gif" /></figure><h4>Notification</h4><p>Almost every application notifies the user in one way or another. That’s why I also want to demonstrate how easily we can create a notification functionally by combining htmx and Alpine.js.</p><p>I’ll create a button that makes a request to the server and shows the notification the server returns to us, but to close the notification I’ll use Alpine.js.</p><p>The following code snippet represents the button:</p><pre>&lt;div class=&quot;has-text-centered&quot;&gt;<br>    &lt;button type=&quot;button&quot;<br>            class=&quot;button is-primary&quot;<br>            hx-get=&quot;@Url.Page(&quot;Notification&quot;, &quot;Notification&quot;)&quot;<br>            hx-target=&quot;#notification&quot;<br>            hx-swap=&quot;innerHTML&quot;&gt;<br>        Show notification<br>    &lt;/button&gt;<br>&lt;/div&gt;</pre><p>And the code of the notification is right below:</p><pre>&lt;div class=&quot;notification is-info&quot; x-data&gt;<br>    &lt;button type=&quot;button&quot;<br>            class=&quot;delete&quot;<br>            aria-label=&quot;close&quot;<br>            x-on:click=&quot;$root.remove()&quot;&gt;&lt;/button&gt;<br>    &lt;strong&gt;@Model.Text&lt;/strong&gt;<br>    &lt;br /&gt;<br>    Generated on the server at @Model.CreatedAt.ToString(&quot;HH:mm:ss&quot;).<br>&lt;/div&gt;</pre><p>When the user clicks the close button, the whole HTML node is removed.</p><p>And here’s the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wZ83vcRfzPreq6I9q4ZOag.gif" /></figure><h4>Float button</h4><p>A floating element is an elegant way to show something to the user when they reach a certain state. For instance, it can be very useful when the user scrolls down through a long list or table with numerous items.</p><p>To illustrate this, let me create a table with a large number of rows, where each row holds Product entity:</p><pre>public enum State<br>{<br>  Active,<br>  Archived,<br>  Deleted<br>}<br><br>public sealed class Product<br>{<br>  public int Id { get; set; }<br><br>  public string Name { get; set; } = string.Empty;<br><br>  public State State { get; set; }<br>}</pre><p>Each entity will be represented as a row in the table:</p><pre>&lt;div id=&quot;products&quot;&gt;<br>    &lt;table class=&quot;table is-fullwidth is-striped is-hoverable&quot;&gt;<br>        &lt;thead&gt;<br>            &lt;tr&gt;<br>                &lt;th&gt;Id&lt;/th&gt;<br>                &lt;th&gt;Name&lt;/th&gt;<br>                &lt;th&gt;Status&lt;/th&gt;<br>            &lt;/tr&gt;<br>        &lt;/thead&gt;<br>        &lt;tbody&gt;<br>            @foreach (var product in Model)<br>            {<br>                &lt;tr&gt;<br>                    &lt;td&gt;@product.Id&lt;/td&gt;<br>                    &lt;td&gt;@product.Name&lt;/td&gt;<br>                    &lt;td&gt;<br>                        &lt;span class=&quot;tag @(product.State switch<br>                                         {<br>                                             State.Deleted =&gt; &quot;is-danger&quot;,<br>                                             State.Archived =&gt; &quot;is-warning&quot;,<br>                                             _ =&gt; &quot;is-light&quot;<br>                                         })&quot;&gt;@product.State&lt;/span&gt;<br>                    &lt;/td&gt;<br>                &lt;/tr&gt;<br>            }<br>        &lt;/tbody&gt;<br>    &lt;/table&gt;<br>&lt;/div&gt;</pre><p>When the user scrolls down, I’m going to show them a button for adding a new product.</p><p>To do that, I’ll create a button that becomes visible only when the user scrolls down to the middle of the table:</p><pre>&lt;div x-data=&quot;{ shown: false }&quot;<br>     x-on:scroll.window=&quot;shown = window.scrollY &gt; 200&quot;&gt;<br>    &lt;button type=&quot;button&quot;<br>            class=&quot;button is-primary is-rounded float-button&quot;<br>            x-show=&quot;shown&quot;<br>            x-cloak<br>            x-transition<br>            hx-post=&quot;@Url.Page(&quot;FloatButton&quot;, &quot;Add&quot;)&quot;<br>            hx-target=&quot;#products&quot;<br>            hx-swap=&quot;outerHTML&quot;&gt;<br>        Add product<br>    &lt;/button&gt;<br>&lt;/div&gt;</pre><p>The view model of the floating div is just one property — shown, which will be changed on the scroll.window event and became visibile or not.</p><p>When the user clicks the button, it will make a request to the following URL — <a href="http://twitter.com/Url">@Url</a>.Page(“FloatButton”, “Add”) and swap the received HTML into the target table #products.</p><p>And here is a result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ExZ0i1LwRjV2MlZnWkenQA.gif" /></figure><h4>Thoughts</h4><p>So if we push all communication between server and client through <strong>htmx</strong>, and leave client-side interactivity to <strong>Alpine.js</strong> — we can build a fantastic app.</p><p>I also love the fact that the htmx and Alpine.js syntax doesn’t clash with Razor, and you really can have just one view (.cshtml) with all the logic in it.</p><p>Now from you, do you already use this? And if so, what do you like most about the combination?</p><p>As always, here’s the <a href="https://github.com/denmaklucky/medium/tree/master/src/2026/FeelSpaApp">link</a> to the repository for you to explore.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea34911a0a47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Union types? No, discriminated union]]></title>
            <link>https://medium.com/@denmaklucky/union-types-no-discriminated-union-0b12b6e7de9b?source=rss-96c11f19481f------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b12b6e7de9b</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[source-generator]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Denis Makarenko]]></dc:creator>
            <pubDate>Mon, 31 Aug 2026 23:01:01 GMT</pubDate>
            <atom:updated>2026-08-31T23:01:01.817Z</atom:updated>
            <content:encoded><![CDATA[<h4>Union types bring an elegant way to work with code, but there are also some disadvantages. If you’re interested in how we can improve it, let’s go under the hood.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*DCcocQXC312a6sUzXrQJDg.png" /></figure><h4>The problem with union types</h4><p>Union types allow developers to create a set of objects. It’s very convenient, especially when a piece of code returns a result which can be different. For instance:</p><pre>public sealed record NotFound;<br><br>public sealed record Created(Guid Id);<br><br>public union CreatePostResult(NotFound, Created);<br><br>public Task&lt;CreatePostResult&gt; CreatePostAsync() <br>{<br>  /***/<br>}</pre><p>However, if you need to serialize and deserialize a union type to send it outside of your app, you will face a problem. When you try to serialize the CreatePostResult, it will work. But when you try to <strong>deserialize it,</strong> you will get an error, something similar to the following:</p><pre>System.Text.Json.JsonException:<br>JSON value type &#39;Object&#39; is ambiguous for union type &#39;CreatePostResult&#39;<br>because multiple case types can use this value type.<br>Specify a custom type classifier to support deserialization.</pre><p>And it happens because the union type <strong>doesn’t provide anything to the JSON serializer</strong> to understand what the exact type is.</p><p>So let’s change that.</p><h4>The solution: discriminated unions</h4><p>The idea is very simple. We need to add something that describes the type <strong>inside the union</strong>, and also provide<strong> specific JSON converter</strong> for the desired type.</p><p>As you know, we can create a <strong>union type</strong> with the union keyword, and also by adding the [Union] attribute and implementing the IUnion interface. And the second way is exactly what we need to go with. But we won’t do it ourselves, let’s leave it to the source generator instead.</p><p>So basically, we will have an attribute by which developers indicate the classes which should be treated as <strong>a discriminated union </strong>and<strong> </strong>the attriubte will take the case types.</p><p>The source generator will use the held case types to generate the constructors and set the discriminator. And inside, the SG should also create a JSON converter that will take care of deserialization and serialization.</p><p>The plan is clean, and the result should be something similar to this code below:</p><pre>public sealed record NotFound;<br><br>public sealed record Created(Guid Id);<br><br>[DiscriminatedUnion(typeof(NotFound), typeof(Created))] //&lt;-- real magic<br>public class CreatePostResult;</pre><p>First, I’ll create a separate project, which I will name <strong>SourceGenerator</strong>, and place there an implementation of IIncrementalGenerator named DiscriminatedUnionIncrementalGenerator:</p><pre>[Generator]<br>public sealed class DiscriminatedUnionIncrementalGenerator<br>  : IIncrementalGenerator<br>{<br>  public void Initialize(IncrementalGeneratorInitializationContext context)<br>  {<br>    throw new NotImplementedException();<br>  } <br>}</pre><p>Next part is adding the attribute, which is the simplest part. The code for adding the attribute is going to be something like this:</p><pre>context.RegisterPostInitializationOutput(initializationContext =&gt;<br>{<br>  initializationContext.AddSource(<br>    &quot;DiscriminatedUnionAttribute.g.cs&quot;,<br>    @&quot;using System;<br><br>namespace DiscriminatedUnions;<br><br>[AttributeUsage(AttributeTargets.Class)]<br>public sealed class DiscriminatedUnionAttribute(params Type[] caseTypes) : Attribute<br>{<br>    public Type[] CaseTypes { get; } = caseTypes;<br>}&quot;);<br>});</pre><p>The code above creates the following class, DiscriminatedUnionAttribute, as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*K7uoAppuSKy3SJQMd1tA_w.png" /></figure><p>Now we need to scan all the classes and find out which of them have the desired attribute. This can be done with the code below:</p><pre>static bool IsSyntaxTargetForGeneration(SyntaxNode node)<br>{<br>  if (node is not ClassDeclarationSyntax classSyntax)<br>  {<br>    return false;<br>  }<br><br>  const string discriminatedUnionAttributeName = &quot;DiscriminatedUnion&quot;;<br><br>  foreach (var attributeSyntax in classSyntax.AttributeLists.SelectMany(attributeList =&gt; attributeList.Attributes))<br>  {<br>    var attributeName = attributeSyntax.Name.ToString();<br><br>    if (string.Equals(discriminatedUnionAttributeName, attributeName, StringComparison.Ordinal) ||<br>        string.Equals($&quot;{discriminatedUnionAttributeName}Attribute&quot;, attributeName, StringComparison.Ordinal))<br>    {<br>      return true;<br>    }<br>  }  <br><br>    return false;<br>}</pre><p>After that, we will have the class syntaxes with the attribute. However, to be able to generate <strong>a discriminated union</strong> according to the plan, the source generator must ensure that the class <strong>is partial</strong>.</p><p>Inside our GenerateDiscriminatedUnionSource method, we will have a skip mechanism for <strong>non-partial classes</strong>:</p><pre>foreach (var classSyntax in classSyntaxes)<br>{<br>  if (!classSyntax.Modifiers.Any(SyntaxKind.PartialKeyword))<br>  {<br>    continue;<br>  }<br><br>  /**/<br>}</pre><p>To get the case types, we need to find the <strong>attribute symbol</strong> first and then find all the types inside. For that, I will use the following code snippet:</p><pre>var discriminatedUnionAttributeSymbol = compilation.GetTypeByMetadataName(&quot;DiscriminatedUnions.DiscriminatedUnionAttribute&quot;);<br><br>/* */<br><br>var discriminatedUnionAttribute = classSymbol<br>                    .GetAttributes()<br>                    .FirstOrDefault(attr =&gt; SymbolEqualityComparer.Default.Equals(attr.AttributeClass, discriminatedUnionAttributeSymbol));<br><br>/* */<br><br>var caseTypes = discriminatedUnionAttribute.ConstructorArguments[0].Values<br>                    .Select(argument =&gt; argument.Value as ITypeSymbol)<br>                    .Where(caseType =&gt; caseType is not null &amp;&amp; caseType.TypeKind != TypeKind.Error)<br>                    .ToList();</pre><blockquote>If you don’t think about it as <strong>Roslyn API</strong>, it’s pretty simple C# code.</blockquote><p>The last thing is to convert these case types into <strong>Roslyn symbols</strong> and use them to generate the code.</p><p>I won’t put all the code in the post, to avoid the unnecessary complexity. However, if you’re interested in that, you can find the full code of DiscriminatedUnionIncrementalGenerator <a href="https://github.com/denmaklucky/medium/tree/master/src/2026/DiscriminatedUnion">here</a>.</p><p>Our actual approach is close to what we were planning:</p><pre>public sealed record NotFound;<br><br>public sealed record Created(Guid Id);<br><br>[DiscriminatedUnion(typeof(NotFound), typeof(Created))]<br>public partial class CreatePostResult;</pre><p>And behind the scenes, the SG will generate the code that takes care of converting marked type into<strong> a real discriminated union</strong>:</p><pre>#nullable enable<br><br>using System;<br>using System.Runtime.CompilerServices;<br>using System.Text.Json;<br>using System.Text.Json.Serialization;<br><br>[Union]<br>[JsonConverter(typeof(CreatePostResult.DiscriminatedUnionJsonConverter))]<br>public partial class CreatePostResult : IUnion<br>{<br>    private readonly object? _value;<br>    private readonly Discriminator _discriminator;<br><br>    private CreatePostResult(object? value, Discriminator discriminator)<br>    {<br>        _value = value;<br>        _discriminator = discriminator;<br>    }<br><br>    public CreatePostResult(global::NotFound value)<br>        : this((object?) value, Discriminator.NotFound)<br>    {<br>    }<br><br>    public CreatePostResult(global::Created value)<br>        : this((object?) value, Discriminator.Created)<br>    {<br>    }<br><br>    public object? Value =&gt; _value;<br><br>    private enum Discriminator<br>    {<br>        NotFound = 0,<br>        Created = 1,<br>    }<br><br>    private sealed class DiscriminatedUnionJsonConverter : JsonConverter&lt;CreatePostResult&gt;<br>    {<br>        private const string Discriminator = &quot;$discriminator&quot;;<br><br>        public override CreatePostResult? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)<br>        {<br>            using var document = JsonDocument.ParseValue(ref reader);<br><br>            var root = document.RootElement;<br><br>            if (root.ValueKind != JsonValueKind.Object)<br>            {<br>                throw new JsonException($&quot;Expected a JSON object for &#39;CreatePostResult&#39; but found {root.ValueKind}.&quot;);<br>            }<br><br>            if (!root.TryGetProperty(Discriminator, out var discriminatorElement) || discriminatorElement.ValueKind != JsonValueKind.String)<br>            {<br>                throw new JsonException($&quot;Missing &#39;{Discriminator}&#39; for &#39;CreatePostResult&#39;.&quot;);<br>            }<br><br>            var discriminator = discriminatorElement.GetString();<br><br>            switch (discriminator)<br>            {<br>                case &quot;NotFound&quot;:<br>                    return new CreatePostResult(root.Deserialize&lt;global::NotFound&gt;(options)!);<br>                case &quot;Created&quot;:<br>                    return new CreatePostResult(root.Deserialize&lt;global::Created&gt;(options)!);<br>                default:<br>                    throw new JsonException($&quot;Unknown &#39;{Discriminator}&#39; value &#39;{discriminator}&#39; for &#39;CreatePostResult&#39;.&quot;);<br>            }<br>        }<br><br>        public override void Write(Utf8JsonWriter writer, CreatePostResult value, JsonSerializerOptions options)<br>        {<br>            writer.WriteStartObject();<br><br>            switch (value._discriminator)<br>            {<br>                case CreatePostResult.Discriminator.NotFound:<br>                    writer.WriteString(Discriminator, &quot;NotFound&quot;);<br>                    WriteValue(writer, JsonSerializer.SerializeToElement&lt;global::NotFound&gt;((global::NotFound) value.Value!, options));<br>                    break;<br>                case CreatePostResult.Discriminator.Created:<br>                    writer.WriteString(Discriminator, &quot;Created&quot;);<br>                    WriteValue(writer, JsonSerializer.SerializeToElement&lt;global::Created&gt;((global::Created) value.Value!, options));<br>                    break;<br>                default:<br>                    throw new JsonException($&quot;Unknown discriminator &#39;{value._discriminator}&#39; on &#39;CreatePostResult&#39;.&quot;);<br>            }<br><br>            writer.WriteEndObject();<br>        }<br><br>        private static void WriteValue(Utf8JsonWriter writer, JsonElement element)<br>        {<br>            if (element.ValueKind != JsonValueKind.Object)<br>            {<br>                throw new JsonException($&quot;A case of &#39;CreatePostResult&#39; must serialize to a JSON object but produced {element.ValueKind}.&quot;);<br>            }<br><br>            foreach (var property in element.EnumerateObject())<br>            {<br>                property.WriteTo(writer);<br>            }<br>        }<br>    }<br>}</pre><blockquote>🤝 Let’s connect on LinkedIn!<br>If you enjoyed this post or want to chat more about it, feel free to connect with me on <a href="https://www.linkedin.com/in/denmaklucky/">LinkedIn</a>. I’d love to hear your thoughts and keep in touch!</blockquote><h4>Final thoughts</h4><p>From what I’ve seen, I honestly love how <strong>union types were designed</strong>, with the window to modify them to your needs. Together with a source generator, developers can create any kind of union type.</p><p>Also, keep in mind that in this post I don’t touch on the topic of the analyzer that would indicate that the [DiscriminatedUnion] was added to a non-partial class or hasn’t case types.</p><p>If you have any questions, or if you’d like to share your thoughts or experiences, feel free to leave a comment down below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b12b6e7de9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unions are here | Union types in C#]]></title>
            <link>https://medium.com/@denmaklucky/unions-are-here-union-types-in-c-cc6b22aeabde?source=rss-96c11f19481f------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc6b22aeabde</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Denis Makarenko]]></dc:creator>
            <pubDate>Sun, 23 Aug 2026 23:01:01 GMT</pubDate>
            <atom:updated>2026-08-23T23:01:01.500Z</atom:updated>
            <content:encoded><![CDATA[<h4>.NET 11 is finally getting union types. If you’re interested in what they’re worth or what’s wrong with them, let’s go under the hood.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*rv4PET_kSZ2FhZ88C7BrlA.png" /></figure><h4>Union types</h4><p>Before we jump into C# union types, let’s start by recalling what union types and discriminated unions are about.</p><p>A union type is one variant from a set of possible types. For instance, let’s look at the following TypeScript snippet:</p><pre>function printId(id: string | number) {<br>  console.log(id);<br>}</pre><p>In the snippet above, the line id: string | number is a union type.</p><p>However, plain union types are rarely used.</p><p>Let’s go back to our example. Imagine you need to use the id union somewhere else. You can’t reuse it as a bare union, and this is where a type alias comes in. You name the union, and then you can use it as a type anywhere in your codebase. So our union type becomes the following:</p><pre>type ID = string | number;<br><br>function printId(id: ID) {<br>  console.log(value);<br>}<br><br>function printUserId(id: ID) {<br>  console.log(value);<br>}</pre><p>There was no way in C# to declare a set of types the way TypeScript does. Instead, we could imitate one with inheritance.</p><p>Let’s go through another example, closer to our own domain. Say you have a <strong>discriminated union</strong> Result:</p><pre>type Success = { kind: &quot;success&quot; };<br>type NotFound = { kind: &quot;notFound&quot; };<br><br>type Result = Success | NotFound;<br><br>function handle(): Result {<br>    return { kind: &quot;success&quot; };<br>}</pre><p>The snippet above is roughly equivalent to the C# below:</p><pre>public abstract class Result;<br><br>public sealed class Success : Result<br>{<br>  public string Kind =&gt; &quot;success&quot;;<br>}<br><br>public sealed class NotFound : Result<br>{<br>  public string Kind =&gt; &quot;notFound&quot;;<br>}<br><br>static Result Handle()<br>{<br>  return new Success();<br>}</pre><p>Although the code looks similar, there’s a fundamental difference between union types and inheritance. A classic class hierarchy is genuinely open: anyone with access to Result <strong>class </strong>can derive a new subclass from it. A union, by contrast, is a closed set — even with access to the Result <strong>union</strong>, you can’t add a new case to it.</p><h4>Current way to have it</h4><p>As I mentioned earlier, unions can be simulated with inheritance — but a classic hierarchy has no way to prevent someone from adding a new subclass. However in C#, a closed hierarchy can be approximated with <strong>nested types</strong>.</p><p>Let’s adjust our example to make it a “real” union type:</p><pre>public abstract class Result<br>{<br>  private Result()<br>  {<br>  }<br><br>  public sealed class Success : Result;<br><br>  public sealed class NotFound : Result;  <br>}</pre><p>This all works well enough, and we can imitate union behaviour — at least some of it.</p><p>But a problem appears as your codebase grows: sooner or later you end up with similar results scattered across different parts of it.</p><p>For instance, say we have several handlers that can all return NotFound:</p><pre>public abstract class GetPostResult<br>{  <br>  public sealed class NotFound : GetPostResult; //&lt;--one &quot;not found&quot; resuslt  <br>}<br><br>public abstract class GetUserResult<br>{<br>  public sealed class NotFound : GetUserResult; //&lt;--another &quot;not found&quot; result<br>}</pre><p>Because of this duplication we break the DRY principle and make our codebase more complex.</p><p>And when I say complexity, I mean code like this:</p><pre>app.MapGet(&quot;posts&quot;, async ([FromServices] GetPostHanlder handler) =&gt;<br>{<br>  var result = await hanlder.InvokeAsync();<br><br>  // this part will be repeated on each endpoint<br>  return result switch<br>  {  <br>    NotFound =&gt; TypedResult.NotFound(),<br>    _ =&gt; TypedResult.Empty()<br>  };<br>});</pre><p>You can work around it, but only if you know for certain that one NotFound really is the same thing as the other. And here we have exactly the problem: GetPostResult.NotFound and GetUserResult.NotFound are two unrelated types.</p><p>If you’re interested in how to avoid the boilerplate above, check out my previous post — I’ve already covered it there:</p><p><a href="https://medium.com/@denmaklucky/dont-return-results-or-typedresults-in-asp-net-core-instead-do-this-b9f6f5598940">Don’t return Results or TypedResults in ASP.NET Core. Instead, do this</a></p><p>The second big problem with unions is <strong>JSON serialization</strong>. Since these aren’t ordinary classes, the default serializer and deserializer won’t handle them out of the box.</p><p>This can be solved with <strong>System.Text.Json</strong>’s [JsonDerivedType] attribute, or with a custom converter that writes <strong>a discriminator property</strong> for each case.</p><p>Let’s apply the attribute and update our example:</p><pre>[JsonDerivedType(typeof(Success), typeDiscriminator: &quot;success&quot;)]<br>[JsonDerivedType(typeof(NotFound), typeDiscriminator: &quot;notFound&quot;)]<br>public abstract class Result<br>{<br>  private Result()<br>  {<br>  }<br><br>  public sealed class Success : Result;<br><br>  public sealed class NotFound : Result;  <br>}</pre><h4>New implementation</h4><p>In .NET 11, Microsoft is introducing a new kind of type — the union type — the <strong>real union</strong> C# developers have been asking for. It comes with a new union keyword.</p><p>Let’s take our example and rewrite it the new way</p><pre>public sealed class Success;<br><br>public sealed class NotFound;<br><br>// a new union type Result<br>public union Result(Success, NotFound);</pre><p>This is very similar to what TypeScript has. Let me illustrate with the example one more time</p><pre>type Success = { kind: &quot;success&quot; };<br>type NotFound = { kind: &quot;notFound&quot; };<br><br>type Result = Success | NotFound;</pre><p>First, let’s work out what a union actually is and how it works in C#. For that, we’ll use the <a href="https://lab.razor.fyi/">following tool</a> to have a low C# code.</p><p>And here’s what our example becomes in lowered C#:</p><pre>[NullableContext(2)]<br>[Nullable(0)]<br>[Union]<br>public struct Result : IUnion<br>{<br> [CompilerGenerated]<br> [DebuggerBrowsable(DebuggerBrowsableState.Never)]<br> private readonly object &lt;Value&gt;k__BackingField;<br><br> public object Value<br> {<br>  [IsReadOnly]<br>  [CompilerGenerated]<br>  get<br>  {<br>   return &lt;Value&gt;k__BackingField;<br>  }<br> }<br><br> [CompilerGenerated]<br> public Result([Nullable(1)] Success value)<br> {<br>  &lt;Value&gt;k__BackingField = value;<br> }<br><br> [CompilerGenerated]<br> public Result([Nullable(1)] NotFound value)<br> {<br>  &lt;Value&gt;k__BackingField = value;<br> }<br>}</pre><p>So the new union is essentially a struct with one constructor per case type.</p><p>When I described how C# developers used to imitate unions, I mentioned two problems that couldn’t be solved. Let’s see how the new <strong>union type</strong> handles them.</p><p>The first one — separate types carrying the same meaning — is gone. We can now define a single result type and share it across both handlers. So the code above becomes something like this:</p><pre>public sealed class NotFound;// &lt;-- only one &quot;not found&quot; result<br><br>public union GetPostResult(NotFound);<br><br>public union GetUserResult(NotFound);</pre><p>Serialization is a different story. What .NET 11 introduces is a type union, not a discriminated one — which means there’s no tag property for the serializer to look at. You can serialize a union and you’ll get whichever case it currently holds, but you can’t deserialize it back.</p><p>This is <a href="https://github.com/dotnet/runtime/issues/127299">by design</a> and it right for <strong>union type</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CjQUUkLUt0YaZn81Fj1IXg.png" /></figure><p>I also want to mention that this silently introduces boxing, since the value is stored as an object.</p><p>So if you have something like this:</p><pre>public union Numbers(int, double, long);</pre><p>Then you’ll pay for boxing and unboxing on every call.</p><blockquote>🤝 Let’s connect on LinkedIn!<br>If you enjoyed this post or want to chat more about it, feel free to connect with me on <a href="https://www.linkedin.com/in/denmaklucky/">LinkedIn</a>. I’d love to hear your thoughts and keep in touch!</blockquote><h4>Instead of a conclusion</h4><p>I really like this feature. Still, something about it feels a little off.</p><p>Now over to you: what do you think? Have you started using it already, and if so, how?</p><p>If you have any questions, or if you’d like to share your thoughts or experiences, feel free to leave a comment down below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc6b22aeabde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build an app with Claude Code — Part 1: manual application development]]></title>
            <link>https://medium.com/@denmaklucky/how-to-build-an-app-with-claude-code-part-1-manual-application-development-630da615c16a?source=rss-96c11f19481f------2</link>
            <guid isPermaLink="false">https://medium.com/p/630da615c16a</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Denis Makarenko]]></dc:creator>
            <pubDate>Thu, 23 Apr 2026 19:27:45 GMT</pubDate>
            <atom:updated>2026-04-23T19:31:12.538Z</atom:updated>
            <content:encoded><![CDATA[<h4>AI is becoming increasingly popular nowadays, making it very important to know how to use it effectively. That’s why, in this series of posts, I’d like to show you <strong>the results</strong> of different approaches to <strong>building an app using</strong> Claude Code.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*nHPjbGuLit721zOAgnzxwQ.png" /></figure><ul><li><strong>→ How to build an app with Claude Code — Part 1: manual application development</strong></li><li><a href="https://medium.com/@denmaklucky/how-to-build-an-app-with-claude-code-part-2-manual-prompt-creating-8c0652f402e2">How to build an app with Claude Code — Part 2: manual prompt creating</a></li><li><a href="https://medium.com/@denmaklucky/how-to-build-an-app-with-claude-code-part-3-creating-prompt-by-interview-6ca4ffc54771">How to build an app with Claude Code — Part 3: creating prompt by interview</a></li></ul><p>To demonstrate the differences between various approaches to building real-world applications using Cloud Code, I’m going to create a simple To-Do list app using <strong>Razor Pages</strong> and <strong>Hydro components</strong>.</p><p>If you’re wondering why I chose such an unconventional combination, the reason is simple: there aren’t many examples of this pairing available to train LLMs. And this is mean that not any of LLM could able to create app with this combination. My theory is that if this approach works well for a rare use case, it will perform even better on more common combinations.</p><p>This won’t be a full guide on creating applications with <strong>Hydro components</strong>; instead, I’ll highlight a few key moments. However, if you’re interested and want to check out the entire source code, you can find it at the following <a href="https://github.com/denmaklucky/medium/tree/master/src/2026/BuildAppWithAI/HumanMadeApp">link</a>.</p><p>Let’s start with the <strong>appsettings</strong>. In my implementation, I’ll place the database connection string in the appsettings.json file and then retrieve it within Program.cs like this:</p><pre>{<br>  &quot;ConnectionStrings&quot;: {<br>    &quot;OwlDb&quot;: &quot;Data Source=owl.db&quot;<br>  }<br>}</pre><pre>builder.Services.AddScoped(_ =&gt; new SqliteConnection(builder.Configuration.GetConnectionString(&quot;OwlDb&quot;)!));</pre><p>This setup allows me to easily swap values in appsettings.json for production using other secret management tools, such as <strong>AWS Secrets Manager</strong> or <strong>Azure Key Vault</strong>.</p><p>Another important aspect is my implementation of the <strong>authentication and authorization</strong> mechanism. Crucially, I provide the userId to the repository to ensure we only fetch the To-Do lists belonging to that specific user.</p><p>Here is the AuthHelper that I use across the application:</p><pre>public static class AuthHelper<br>{<br>    public static Task SignInAsync(HttpContext context,<br>        string userId,<br>        string username)<br>    {<br>        var claims = new List&lt;Claim&gt;<br>        {<br>            new (ClaimTypes.NameIdentifier, userId),<br>            new (ClaimTypes.Name, username)<br>        };<br><br>        var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);<br>        var principal = new ClaimsPrincipal(identity);<br><br>        return context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);<br>    }<br><br>    public static Task SignOutAsync(HttpContext context)<br>    {<br>        return context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);<br>    }<br><br>    public static string? GetUserId(HttpContext context)<br>    {<br>        return context.User.FindFirstValue(ClaimTypes.NameIdentifier);<br>    }<br><br>    public static string? GetUsername(HttpContext context)<br>    {<br>        return context.User.FindFirstValue(ClaimTypes.Name);<br>    }<br><br>    public static bool IsAuthenticated(HttpContext context)<br>    {<br>        return context.User.Identity?.IsAuthenticated ?? false;<br>    }<br>}</pre><p>I’ve also included the members of the ToDoRepository to demonstrate how I actually implement this logic within the application:</p><pre>public sealed class ToDoRepository(SqliteConnection connection)<br>{<br>    public async Task CreateAsync(Guid userId, string title)<br>    {<br>        //Implementation<br>    }<br><br>    public async Task ToggleAsync(Guid userId, Guid toDoId)<br>    {<br>        //Implementation<br>    }<br><br>    public async Task DeleteAsync(Guid userId, Guid toDoId)<br>    {<br>        //Implementation<br>    }<br><br>    public async Task&lt;List&lt;ToDo&gt;&gt; ListAsync(Guid userId,<br>      bool? completedFilter = null)<br>    {<br>        //Implementation<br>    }<br><br>    public async Task&lt;int&gt; GetCompletedToDoCountAsync(Guid userId)<br>    {<br>        //Implementation<br>    }    <br>}</pre><p>Additionally, instead of using the <strong>Result pattern</strong>, I’m using <strong>Discriminated Unions (DU)</strong>. Here is what that looks like:</p><pre>// RegisterUserResult.cs<br>public abstract record RegisterUserResult<br>{<br>    public sealed record UserAlreadyRegistered :  RegisterUserResult;<br><br>    public sealed record Success(Guid Id) :  RegisterUserResult;<br>}<br><br>//GetUserResult.cs<br>public abstract record GetUserResult<br>{<br>    public sealed record NotFound : GetUserResult;<br><br>    public sealed record Success(string UserId, string Hash) : GetUserResult;<br>}<br><br>//UserRepository.cs<br>public sealed class UserRepository(SqliteConnection connection)<br>{<br>    public async Task&lt;RegisterUserResult&gt; RegisterAsync(string username, string hashedPassword)<br>    {<br>        //Implementation<br>    }<br><br>    public async Task&lt;GetUserResult&gt; GetAsync(string username)<br>    {<br>        //Implementation<br>    }<br>}</pre><p>The final piece of the puzzle is my use of <strong>isolated CSS</strong>. It’s incredibly useful because it allows you to keep all related files together in one place:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*uPzXDRhFWA8XhDpZQz-HGg.png" /></figure><p>As a result of everything we’ve set up, you can see the final result here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yx-dE0_mpH6DUkh9b4ItWw.gif" /></figure><blockquote>🤝 Let’s connect on LinkedIn!<br>If you enjoyed this post or want to chat more about it, feel free to connect with me on <a href="https://www.linkedin.com/in/denmaklucky/">LinkedIn</a>. I’d love to hear your thoughts and keep in touch!</blockquote><p>In the <a href="https://medium.com/@denmaklucky/how-to-build-an-app-with-claude-code-part-2-manual-prompt-creating-8c0652f402e2">next post</a>, you’ll see what <strong>Claude Code</strong> can create using just a single prompt.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=630da615c16a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build an app with Claude Code — Part 2: manual prompt creating]]></title>
            <link>https://medium.com/@denmaklucky/how-to-build-an-app-with-claude-code-part-2-manual-prompt-creating-8c0652f402e2?source=rss-96c11f19481f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c0652f402e2</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Denis Makarenko]]></dc:creator>
            <pubDate>Wed, 22 Apr 2026 18:23:24 GMT</pubDate>
            <atom:updated>2026-04-23T19:31:43.662Z</atom:updated>
            <content:encoded><![CDATA[<h4>AI is becoming increasingly popular nowadays, making it very important to know how to use it effectively. That’s why, in this series of posts, I’d like to show you <strong>the results</strong> of different approaches to <strong>building an app using</strong> Claude Code.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*nHPjbGuLit721zOAgnzxwQ.png" /></figure><ul><li><a href="https://medium.com/@denmaklucky/how-to-build-an-app-with-claude-code-part-1-manual-application-development-630da615c16a">How to build an app with Claude Code — Part 1: manual application development</a></li><li><strong>→ How to build an app with Claude Code — Part 2: one-shot approach</strong></li><li><a href="https://medium.com/@denmaklucky/how-to-build-an-app-with-claude-code-part-3-creating-prompt-by-interview-6ca4ffc54771">How to build an app with Claude Code — Part 3: creating prompt by interview</a></li></ul><p>In my previous post, I created a simple To-Do list using <strong>Razor Pages</strong> and <strong>Hydro components</strong>. Now, let’s try to build a similar application using Claude Code and a single mega-prompt.</p><p>I am currently using the latest version of Claude Code available at the time of writing (2.1.116) and Opus 4.6:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XVFoTrjwmXjgCZCGUVhrRg.png" /></figure><blockquote>I used <strong>winget</strong> to install Claude Code on my PC, which is incredibly convenient; with just one command, you have Claude Code ready to go. You can install it using the following command: winget install Anthropic.ClaudeCode <br>And you can upgrade it using the following command: winget upgrade Anthropic.ClaudeCode</blockquote><p>Now, let’s take a look at our mega-prompt.</p><p>First of all, I will define the role that Claude Code should assume:</p><pre>You are a .NET developer who specializes in Razor Pages applications.<br>You write clean, Microsoft-guideline-compliant code following best practices.<br>Your applications feel polished — with great design and incredible UI/UX.</pre><p>Next, I will specify the concept of the application:</p><pre>An ToDo list application where users can sign up and sign in into application.<br>Can create, view, delete and update their ToDos.</pre><p>And, of course, the tech stack:</p><pre>| Concern | Technology |<br>|---|---|<br>| Framework | .NET 11 |<br>| Component | **HydroComponent** — a component that bring SPA feeling without SPA |<br>| Styling | Bootstrap |<br>| Database | use SQLite and dapper over it |</pre><p>If you’d like to see the full prompt, you can find it <a href="https://github.com/denmaklucky/medium/blob/master/src/2026/BuildAppWithAI/OneShotAIApp/prompt.md">here</a>.</p><p>When my promt was done I ask Claude Code to create an app by on the promt.</p><p>After some time, Claude Code finished writing the app, but it <strong>couldn’t</strong> build successfully. Because of this, I had to fix the errors myself in order to test the application.</p><p>I noticed is that Claude Code couldn’t resolve some using statements; essentially, it failed to add the necessary namespaces to the files, so I had to resolve those issues manually.</p><p>The first critical issue I noticed was that Claude Code forgot to add the following code app.UseStaticFiles(); for handling static files:</p><pre>app.UseHttpsRedirection();<br>app.UseRouting();<br><br>app.UseAuthentication();<br>app.UseAuthorization();<br>app.MapStaticAssets();<br>app.MapRazorPages()<br>   .WithStaticAssets();<br>app.Run();</pre><p>Because of the issue mentioned above, <strong>Hydro</strong> was unable to function correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*lZSQcqS3ZHUzRoeeecvwIw.png" /></figure><p>I also encountered a problem during database querying. For some reason, Claude Code attempted to convert string to GUID .</p><p>There were a few other minor UI issues that I faced, but in general, the application works.</p><p>You can see how the final result looks below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6HNVw8pBnicDlvtWnPdVFA.gif" /></figure><blockquote>🤝 Let’s connect on LinkedIn!<br>If you enjoyed this post or want to chat more about it, feel free to connect with me on <a href="https://www.linkedin.com/in/denmaklucky/">LinkedIn</a>. I’d love to hear your thoughts and keep in touch!</blockquote><p>To check the complete code created by Claude Code, please visit the <a href="https://github.com/denmaklucky/medium/tree/master/src/2026/BuildAppWithAI/OneShotAIApp">link</a>.</p><p>In general, this approach is fine, but the most difficult part is creating the “mega-prompt” itself. It is very challenging, especially if you aren’t exactly sure what you want yet.</p><p>In my <a href="https://medium.com/@denmaklucky/how-to-build-an-app-with-claude-code-part-3-creating-prompt-by-interview-6ca4ffc54771">next pos</a>t, I will try to create an application using an interview approach, which should significantly improve my interaction with Claude Code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c0652f402e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>