<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Dmitry Dorogoy</title>
    <description>The latest articles on Forem by Dmitry Dorogoy (@dimonsmart).</description>
    <link>https://forem.com/dimonsmart</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F51323%2F32c15d3b-9f4f-4c25-ab65-4a5e55f33aab.jpg</url>
      <title>Forem: Dmitry Dorogoy</title>
      <link>https://forem.com/dimonsmart</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/dimonsmart"/>
    <language>en</language>
    <item>
      <title>C#: Does a Static Constructor Always Run First?</title>
      <dc:creator>Dmitry Dorogoy</dc:creator>
      <pubDate>Tue, 03 Mar 2026 17:59:09 +0000</pubDate>
      <link>https://forem.com/dimonsmart/c-does-a-static-constructor-always-run-first-48mb</link>
      <guid>https://forem.com/dimonsmart/c-does-a-static-constructor-always-run-first-48mb</guid>
      <description>&lt;p&gt;There’s a common misconception — and it often shows up as an interview question:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;On the first access to a type, the very first thing that runs is the type’s static constructor.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;But if a static field is initialized with an instance of the &lt;em&gt;same&lt;/em&gt; type, the order flips: the instance constructor can run &lt;strong&gt;before&lt;/strong&gt; the static constructor. This is not a bug — it’s defined by the CLI/ECMA specification.&lt;/p&gt;

&lt;h2&gt;
  
  
  Minimal example
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;MyLogger&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="n"&gt;MyLogger&lt;/span&gt; &lt;span class="n"&gt;inner&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nf"&gt;MyLogger&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

    &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="nf"&gt;MyLogger&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;Console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;WriteLine&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Static"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="nf"&gt;MyLogger&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;Console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;WriteLine&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Instance"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The expectation is often:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;code&gt;Static&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Instance&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Actual output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Instance
Static
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  What the specification actually guarantees
&lt;/h2&gt;

&lt;p&gt;It’s important to separate two concepts:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;static field initializers&lt;/strong&gt; (field initializers),&lt;/li&gt;
&lt;li&gt;the &lt;strong&gt;body of the static constructor&lt;/strong&gt; (&lt;code&gt;static MyLogger() { ... }&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;During type initialization, code runs in a fixed order:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;first — static field initializers (in declaration order),&lt;/li&gt;
&lt;li&gt;then — the body of the &lt;code&gt;static&lt;/code&gt; constructor.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;So if a static field initializer calls &lt;code&gt;new MyLogger()&lt;/code&gt;, it triggers the &lt;strong&gt;instance constructor&lt;/strong&gt; &lt;em&gt;before&lt;/em&gt; execution reaches &lt;code&gt;Console.WriteLine("Static")&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why this can become a bug
&lt;/h2&gt;

&lt;p&gt;The problem appears when the instance constructor (or anything it calls) assumes the static part of the type is already “up”. But it isn’t — execution is still inside static field initialization.&lt;/p&gt;

&lt;p&gt;A real crash example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Service&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="n"&gt;ConnectionString&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="n"&gt;Service&lt;/span&gt; &lt;span class="n"&gt;Instance&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nf"&gt;Service&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

    &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="nf"&gt;Service&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;ConnectionString&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;LoadFromConfig&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="nf"&gt;Service&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// ConnectionString is still null&lt;/span&gt;
        &lt;span class="n"&gt;Console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;WriteLine&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ConnectionString&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Length&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, &lt;code&gt;Instance = new Service()&lt;/code&gt; runs before &lt;code&gt;ConnectionString&lt;/code&gt; is assigned, so accessing &lt;code&gt;Length&lt;/code&gt; will throw a &lt;code&gt;NullReferenceException&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to fix it (and how not to write it)
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1) Don’t create instances in static field initializers when there are dependencies
&lt;/h3&gt;

&lt;p&gt;The simplest way to control the order is to move the creation into the static constructor &lt;em&gt;after&lt;/em&gt; setting up the required state:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;MyLogger&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="n"&gt;MyLogger&lt;/span&gt; &lt;span class="n"&gt;inner&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="nf"&gt;MyLogger&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// first: any static setup&lt;/span&gt;
        &lt;span class="n"&gt;inner&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nf"&gt;MyLogger&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
        &lt;span class="n"&gt;Console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;WriteLine&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Static"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="nf"&gt;MyLogger&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;Console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;WriteLine&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Instance"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2) Use &lt;code&gt;Lazy&amp;lt;T&amp;gt;&lt;/code&gt; for lazy and thread-safe initialization
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="k"&gt;readonly&lt;/span&gt; &lt;span class="n"&gt;Lazy&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;MyLogger&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;inner&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="p"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nf"&gt;MyLogger&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;

&lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="n"&gt;MyLogger&lt;/span&gt; &lt;span class="n"&gt;Inner&lt;/span&gt; &lt;span class="p"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;inner&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Value&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This makes the creation moment explicit: the object is created on the first access to &lt;code&gt;Inner&lt;/code&gt;, not during type initialization.&lt;/p&gt;

&lt;h3&gt;
  
  
  3) Minimize side effects in constructors
&lt;/h3&gt;

&lt;p&gt;If a constructor pulls config, logging, service locator, DI, etc., the risk of “early” access to uninitialized statics is higher.&lt;/p&gt;

&lt;h2&gt;
  
  
  Takeaway
&lt;/h2&gt;

&lt;p&gt;“Static constructors always run first” is too rough — and misleading in this case.&lt;/p&gt;

&lt;p&gt;The correct model is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;on first use of a type, &lt;strong&gt;type initialization&lt;/strong&gt; happens;&lt;/li&gt;
&lt;li&gt;inside it, &lt;strong&gt;static field initializers run first&lt;/strong&gt; (in declaration order);&lt;/li&gt;
&lt;li&gt;and only &lt;strong&gt;after that&lt;/strong&gt; does the body of the &lt;code&gt;static&lt;/code&gt; constructor run.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That’s why &lt;code&gt;static Foo x = new Foo()&lt;/code&gt; can trigger the &lt;strong&gt;instance constructor&lt;/strong&gt; before any code inside &lt;code&gt;static Foo()&lt;/code&gt; executes.&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>dotnet</category>
    </item>
    <item>
      <title>Surprise: You Can "Intercept" the C# lock Statement</title>
      <dc:creator>Dmitry Dorogoy</dc:creator>
      <pubDate>Tue, 17 Feb 2026 22:09:04 +0000</pubDate>
      <link>https://forem.com/dimonsmart/surprise-you-can-intercept-the-c-lock-statement-14n</link>
      <guid>https://forem.com/dimonsmart/surprise-you-can-intercept-the-c-lock-statement-14n</guid>
      <description>&lt;h1&gt;
  
  
  You can “hijack” &lt;code&gt;lock&lt;/code&gt; in C#. Here is how it works, and why you should not do it.
&lt;/h1&gt;

&lt;p&gt;Many developers think &lt;code&gt;lock&lt;/code&gt; is some kind of runtime “magic”. It is not. In most cases it is plain syntax sugar: the compiler rewrites it into calls to &lt;code&gt;System.Threading.Monitor&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;That rewrite has an ugly edge case. If your project defines its own &lt;code&gt;System.Threading.Monitor&lt;/code&gt;, the compiler can bind to &lt;em&gt;your&lt;/em&gt; type instead of the BCL one. In other words, you can change what &lt;code&gt;lock&lt;/code&gt; means.&lt;/p&gt;

&lt;p&gt;This is a party trick. Also a foot-gun. Treat it as a cautionary tale, not a technique.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: starting with &lt;strong&gt;.NET 9&lt;/strong&gt; and &lt;strong&gt;C# 13&lt;/strong&gt;, &lt;code&gt;lock&lt;/code&gt; has a special fast path when the expression is a &lt;code&gt;System.Threading.Lock&lt;/code&gt;. In that case, it compiles to &lt;code&gt;using (x.EnterScope()) { ... }&lt;/code&gt; instead of &lt;code&gt;Monitor.Enter/Exit&lt;/code&gt;.&lt;br&gt;&lt;br&gt;
The hijack shown below applies to the classic &lt;code&gt;lock (object)&lt;/code&gt; path.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  What the compiler generates for &lt;code&gt;lock&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;For the classic &lt;code&gt;lock (obj) { ... }&lt;/code&gt; case, the C# compiler generates code equivalent to this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="kt"&gt;object&lt;/span&gt; &lt;span class="n"&gt;_lockObj&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;obj&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kt"&gt;bool&lt;/span&gt; &lt;span class="n"&gt;_lockWasTaken&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="k"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;try&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Threading&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Monitor&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;Enter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;_lockObj&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;ref&lt;/span&gt; &lt;span class="n"&gt;_lockWasTaken&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="c1"&gt;// Your code...&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="k"&gt;finally&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;_lockWasTaken&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Threading&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Monitor&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;Exit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;_lockObj&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So &lt;code&gt;lock&lt;/code&gt; is not “special” at runtime. It is a compiler pattern that expands into known calls.&lt;/p&gt;




&lt;h2&gt;
  
  
  The hijack trick
&lt;/h2&gt;

&lt;p&gt;If you define a type with the same fully-qualified name as the BCL type, you can make the compiler call your methods.&lt;/p&gt;

&lt;p&gt;Minimal example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;LINQPad snippet: &lt;a href="https://share.linqpad.net/dmgs488o.linq" rel="noopener noreferrer"&gt;https://share.linqpad.net/dmgs488o.linq&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="k"&gt;using&lt;/span&gt; &lt;span class="nn"&gt;System&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Program&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="k"&gt;readonly&lt;/span&gt; &lt;span class="kt"&gt;object&lt;/span&gt; &lt;span class="n"&gt;_sync&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

    &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="k"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;Main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// Looks like a normal lock, but it is hijacked.&lt;/span&gt;
        &lt;span class="k"&gt;lock&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;_sync&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;Console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;WriteLine&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Working inside the lock..."&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// We "fake" the system namespace and class.&lt;/span&gt;
&lt;span class="k"&gt;namespace&lt;/span&gt; &lt;span class="nn"&gt;System.Threading&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Monitor&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="k"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;Enter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;object&lt;/span&gt; &lt;span class="n"&gt;obj&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;ref&lt;/span&gt; &lt;span class="kt"&gt;bool&lt;/span&gt; &lt;span class="n"&gt;lockTaken&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;Console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;WriteLine&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Hijacked: Enter() was called"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
            &lt;span class="n"&gt;lockTaken&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="k"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// Important: otherwise Exit() won't be called.&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="k"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;Exit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;object&lt;/span&gt; &lt;span class="n"&gt;obj&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;Console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;WriteLine&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Hijacked: Exit() was called"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run it and you will see the &lt;code&gt;Hijacked:&lt;/code&gt; messages. That is your proof that the compiler bound &lt;code&gt;lock&lt;/code&gt; to &lt;strong&gt;your&lt;/strong&gt; &lt;code&gt;System.Threading.Monitor&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why does this work?
&lt;/h3&gt;

&lt;p&gt;Because name resolution happens at compile time.&lt;/p&gt;

&lt;p&gt;Your compilation contains a &lt;code&gt;System.Threading.Monitor&lt;/code&gt; type, and there is also one in referenced assemblies. The compiler sees both and chooses one. If it picks yours, the rewrite still happens, but it targets your methods.&lt;/p&gt;

&lt;p&gt;This is exactly what the compiler warning is trying to tell you.&lt;/p&gt;




&lt;h2&gt;
  
  
  Do not ignore the warning
&lt;/h2&gt;

&lt;p&gt;This code should produce &lt;strong&gt;CS0436&lt;/strong&gt;. In this scenario it is not “noise”. It is the whole point.&lt;/p&gt;

&lt;p&gt;CS0436 means:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;there is a conflict between a type in your compilation and an imported type&lt;/li&gt;
&lt;li&gt;the compiler will use the type from your compilation&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If your custom &lt;code&gt;Enter&lt;/code&gt; method does not actually lock, then multiple threads can run inside the supposed critical section at the same time. That breaks invariants and causes the worst kind of bugs: rare races that are hard to reproduce and disappear under the debugger.&lt;/p&gt;

&lt;p&gt;It can also happen accidentally:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;a helper class is named &lt;code&gt;Monitor&lt;/code&gt; and ends up in the wrong namespace&lt;/li&gt;
&lt;li&gt;a dependency ships a conflicting type&lt;/li&gt;
&lt;li&gt;warnings are suppressed globally and CS0436 is missed&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you ever see CS0436 around &lt;code&gt;System.Threading.Monitor&lt;/code&gt;, stop and investigate.&lt;/p&gt;




&lt;h2&gt;
  
  
  A safer goal: measure lock contention
&lt;/h2&gt;

&lt;p&gt;If your goal is observability, not sabotage, there is a better approach: measure contention without touching &lt;code&gt;lock&lt;/code&gt; at all.&lt;/p&gt;

&lt;p&gt;.NET exposes runtime events for monitor contention:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;ContentionStart_V2&lt;/code&gt; has event id &lt;strong&gt;81&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;ContentionStop_V1&lt;/code&gt; has event id &lt;strong&gt;91&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;ContentionStop_V1&lt;/code&gt; includes &lt;code&gt;DurationNs&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;the keyword is &lt;code&gt;ContentionKeyword&lt;/code&gt; (&lt;strong&gt;0x4000&lt;/strong&gt;)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can listen to these events via &lt;code&gt;EventListener&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;LINQPad snippet: &lt;a href="https://share.linqpad.net/6iebniko.linq" rel="noopener noreferrer"&gt;https://share.linqpad.net/6iebniko.linq&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="k"&gt;using&lt;/span&gt; &lt;span class="nn"&gt;System&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;using&lt;/span&gt; &lt;span class="nn"&gt;System.Diagnostics.Tracing&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;using&lt;/span&gt; &lt;span class="nn"&gt;System.Threading&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;sealed&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;LockMonitor&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;EventListener&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="n"&gt;TotalWaitTimeNs&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;_durationIndex&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="p"&gt;-&lt;/span&gt;&lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;protected&lt;/span&gt; &lt;span class="k"&gt;override&lt;/span&gt; &lt;span class="k"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;OnEventSourceCreated&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;EventSource&lt;/span&gt; &lt;span class="n"&gt;source&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;source&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Name&lt;/span&gt; &lt;span class="p"&gt;==&lt;/span&gt; &lt;span class="s"&gt;"Microsoft-Windows-DotNETRuntime"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nf"&gt;EnableEvents&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;source&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;EventLevel&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Informational&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;EventKeywords&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="m"&gt;0x4000&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;protected&lt;/span&gt; &lt;span class="k"&gt;override&lt;/span&gt; &lt;span class="k"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;OnEventWritten&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;EventWrittenEventArgs&lt;/span&gt; &lt;span class="n"&gt;eventData&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// ContentionStop_V1&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;eventData&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;EventId&lt;/span&gt; &lt;span class="p"&gt;!=&lt;/span&gt; &lt;span class="m"&gt;91&lt;/span&gt; &lt;span class="p"&gt;||&lt;/span&gt; &lt;span class="n"&gt;eventData&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;PayloadNames&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="k"&gt;null&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;_durationIndex&lt;/span&gt; &lt;span class="p"&gt;&amp;lt;&lt;/span&gt; &lt;span class="m"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;_durationIndex&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;eventData&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;PayloadNames&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;IndexOf&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"DurationNs"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;_durationIndex&lt;/span&gt; &lt;span class="p"&gt;&amp;lt;&lt;/span&gt; &lt;span class="m"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="c1"&gt;// DurationNs is documented as a Double. Convert and keep nanoseconds as a long for easy accumulation.&lt;/span&gt;
        &lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;durationNs&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;long&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="n"&gt;Convert&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;ToDouble&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;eventData&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Payload&lt;/span&gt;&lt;span class="p"&gt;![&lt;/span&gt;&lt;span class="n"&gt;_durationIndex&lt;/span&gt;&lt;span class="p"&gt;]!);&lt;/span&gt;
        &lt;span class="n"&gt;Interlocked&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;Add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;ref&lt;/span&gt; &lt;span class="n"&gt;TotalWaitTimeNs&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;durationNs&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  What you get with this approach
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;lock&lt;/code&gt; remains a real lock.&lt;/li&gt;
&lt;li&gt;You collect how much time threads spend waiting.&lt;/li&gt;
&lt;li&gt;You can compare “good” and “bad” code paths and see contention clearly.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you need a deeper report (per lock object, stack traces, timelines), use tools like &lt;code&gt;dotnet-trace&lt;/code&gt;, PerfView, or ETW/EventPipe-based profilers. The small &lt;code&gt;EventListener&lt;/code&gt; above is a good minimal demo.&lt;/p&gt;




&lt;h2&gt;
  
  
  Takeaway
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;lock&lt;/code&gt; is compiler sugar that usually expands into &lt;code&gt;System.Threading.Monitor.Enter/Exit&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;A type name collision can change what the compiler emits. CS0436 warns you that you are changing meaning.&lt;/li&gt;
&lt;li&gt;Hijacking &lt;code&gt;lock&lt;/code&gt; is a neat demo, but a terrible idea in real code.&lt;/li&gt;
&lt;li&gt;For diagnostics, prefer contention events and proper tooling instead of tricks.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>csharp</category>
      <category>dotnet</category>
      <category>dotnetcore</category>
    </item>
    <item>
      <title>C# dynamic is a trap door: stop the leaks before they spread (Must read for Dapper users)</title>
      <dc:creator>Dmitry Dorogoy</dc:creator>
      <pubDate>Wed, 14 Jan 2026 10:56:30 +0000</pubDate>
      <link>https://forem.com/dimonsmart/c-dynamic-is-a-trap-door-stop-the-leaks-before-they-spread-must-read-for-dapper-users-1b0l</link>
      <guid>https://forem.com/dimonsmart/c-dynamic-is-a-trap-door-stop-the-leaks-before-they-spread-must-read-for-dapper-users-1b0l</guid>
      <description>&lt;p&gt;In C#, &lt;code&gt;dynamic&lt;/code&gt; can be handy at boundaries. The problem is that it can silently leak into places where you expect static typing, and your method signatures can still look perfectly safe.&lt;/p&gt;

&lt;p&gt;I ran into these leaks in real projects, so I built a small Roslyn analyzer to catch them early. I am the author of &lt;strong&gt;&lt;a href="https://github.com/DimonSmart/DynamicLeakAnalyzer" rel="noopener noreferrer"&gt;DynamicLeakAnalyzer&lt;/a&gt;&lt;/strong&gt; (NuGet: &lt;code&gt;DimonSmart.DynamicLeakAnalyzer&lt;/code&gt;), and this post explains the problem it targets and how to fix leaks at the boundary.&lt;/p&gt;

&lt;h2&gt;
  
  
  What &lt;code&gt;dynamic&lt;/code&gt; really means
&lt;/h2&gt;

&lt;p&gt;In C#, &lt;code&gt;dynamic&lt;/code&gt; is a &lt;strong&gt;static type&lt;/strong&gt;, but it &lt;strong&gt;bypasses compile-time type checking&lt;/strong&gt; for the expression. Member access, overload resolution, operators, and conversions are bound at runtime.&lt;/p&gt;

&lt;p&gt;At runtime, values still flow as &lt;code&gt;object&lt;/code&gt;. The difference is that the compiler emits runtime binding (DLR call sites). Those call sites have caching, so repeated calls can get faster after the first bind.&lt;/p&gt;

&lt;h2&gt;
  
  
  How "dynamic contagion" happens
&lt;/h2&gt;

&lt;p&gt;Two patterns make leaks hard to spot during review:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Invisible runtime work:&lt;/strong&gt; member access and conversions happen at runtime.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Deceptive signatures:&lt;/strong&gt; a method can return &lt;code&gt;int&lt;/code&gt; and still perform dynamic conversions inside.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;var&lt;/code&gt; can silently become &lt;code&gt;dynamic&lt;/code&gt;:&lt;/strong&gt; when the right side is dynamic, the inferred type becomes dynamic.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here is a small example that shows both problems. The method looks fully static and returns &lt;code&gt;int&lt;/code&gt;, yet dynamic enters through the parameter.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Program&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;GetX&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="k"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;Main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kt"&gt;dynamic&lt;/span&gt; &lt;span class="n"&gt;prm&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="m"&gt;123&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;GetX&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;prm&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// DSM001: implicit dynamic conversion at runtime&lt;/span&gt;
        &lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;GetX&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;prm&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// DSM002: b becomes dynamic because the invocation is dynamic&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In real code, &lt;code&gt;prm&lt;/code&gt; is often not a local variable. It can be an object passed into the method, and dynamic can hide in a field or property, for example &lt;code&gt;prm.Payload.Id&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Dapper trap
&lt;/h2&gt;

&lt;p&gt;Dapper makes it easy to introduce &lt;code&gt;dynamic&lt;/code&gt; without noticing it. Calling &lt;code&gt;QueryFirst&lt;/code&gt; without &lt;code&gt;&amp;lt;T&amp;gt;&lt;/code&gt; returns a dynamic row object (usually &lt;code&gt;DapperRow&lt;/code&gt;), so property access becomes dynamic.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="k"&gt;using&lt;/span&gt; &lt;span class="nn"&gt;Dapper&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;using&lt;/span&gt; &lt;span class="nn"&gt;System.Data&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Repo&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;GetActiveUserId&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;IDbConnection&lt;/span&gt; &lt;span class="n"&gt;cn&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// QueryFirst() without &amp;lt;T&amp;gt; returns a dynamic row (DapperRow).&lt;/span&gt;
        &lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;cn&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;QueryFirst&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"select Id from Users where IsActive = 1"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

        &lt;span class="c1"&gt;// row.Id is dynamic, the conversion to int happens at runtime.&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Id&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// DSM001&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This kind of code often passes reviews because the signature says &lt;code&gt;int&lt;/code&gt;. The dynamic binding is hidden in the middle.&lt;/p&gt;

&lt;h3&gt;
  
  
  Safer alternatives in Dapper
&lt;/h3&gt;

&lt;p&gt;Prefer typed APIs at the boundary:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;cn&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;QuerySingle&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;(&lt;/span&gt;&lt;span class="s"&gt;"select Id from Users where IsActive = 1"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or map to a small DTO:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;sealed&lt;/span&gt; &lt;span class="k"&gt;record&lt;/span&gt; &lt;span class="nc"&gt;UserId&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;Id&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;cn&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;QuerySingle&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;UserId&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;(&lt;/span&gt;&lt;span class="s"&gt;"select Id from Users where IsActive = 1"&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="n"&gt;Id&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you really must use a dynamic row, kill it immediately:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;cn&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;QueryFirst&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"select Id from Users where IsActive = 1"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Id&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The goal is not "never use dynamic". The goal is "stop the leak at the boundary".&lt;/p&gt;

&lt;h2&gt;
  
  
  The solution: DynamicLeakAnalyzer
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;DynamicLeakAnalyzer&lt;/strong&gt; is a Roslyn analyzer that makes these leaks loud before they spread.&lt;/p&gt;

&lt;p&gt;It reports two rules:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;DSM001 (Implicit dynamic conversion):&lt;/strong&gt; a &lt;code&gt;dynamic&lt;/code&gt; expression is used where a static type is expected (return, assignment, argument, etc.). The code compiles, but the conversion happens at runtime.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;DSM002 (&lt;code&gt;var&lt;/code&gt; inferred as &lt;code&gt;dynamic&lt;/code&gt;):&lt;/strong&gt; &lt;code&gt;var&lt;/code&gt; captures a dynamic result and becomes dynamic.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Install and enforce
&lt;/h2&gt;

&lt;p&gt;Add the analyzer:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;dotnet add package DimonSmart.DynamicLeakAnalyzer
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Make warnings hurt using &lt;code&gt;.editorconfig&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ini"&gt;&lt;code&gt;&lt;span class="py"&gt;root&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s"&gt;true&lt;/span&gt;

&lt;span class="nn"&gt;[*.cs]&lt;/span&gt;
&lt;span class="py"&gt;dotnet_diagnostic.DSM001.severity&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s"&gt;error&lt;/span&gt;
&lt;span class="py"&gt;dotnet_diagnostic.DSM002.severity&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s"&gt;error&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Where &lt;code&gt;dynamic&lt;/code&gt; is fine, and where it is not
&lt;/h2&gt;

&lt;p&gt;Good boundary examples:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;COM interop&lt;/li&gt;
&lt;li&gt;JSON adapters and glue code&lt;/li&gt;
&lt;li&gt;database adapters (including dynamic Dapper rows)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Avoid &lt;code&gt;dynamic&lt;/code&gt; in:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;core domain logic&lt;/li&gt;
&lt;li&gt;hot loops&lt;/li&gt;
&lt;li&gt;libraries meant for other developers&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Next steps
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Run the analyzer on a real codebase and see where dynamic leaks already exist.&lt;/li&gt;
&lt;li&gt;If you use Dapper, search for &lt;code&gt;QueryFirst(&lt;/code&gt; and non-generic &lt;code&gt;Query(&lt;/code&gt; calls that return dynamic rows.&lt;/li&gt;
&lt;li&gt;If you have false positives or missed cases, open an issue with a minimal repro.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>csharp</category>
      <category>roslyn</category>
      <category>dapper</category>
      <category>dotnet</category>
    </item>
    <item>
      <title>[Boost]</title>
      <dc:creator>Dmitry Dorogoy</dc:creator>
      <pubDate>Tue, 03 Jun 2025 17:57:20 +0000</pubDate>
      <link>https://forem.com/dimonsmart/-3o44</link>
      <guid>https://forem.com/dimonsmart/-3o44</guid>
      <description>&lt;div class="ltag__link--embedded"&gt;
  &lt;div class="crayons-story "&gt;
  &lt;a href="https://dev.to/dimonsmart/how-i-created-a-handy-mcp-server-in-c-to-retrieve-nuget-package-information-1gf5" class="crayons-story__hidden-navigation-link"&gt;How I Created a Handy MCP Server in C# to Retrieve NuGet Package Information&lt;/a&gt;


  &lt;div class="crayons-story__body crayons-story__body-full_post"&gt;
    &lt;div class="crayons-story__top"&gt;
      &lt;div class="crayons-story__meta"&gt;
        &lt;div class="crayons-story__author-pic"&gt;

          &lt;a href="/dimonsmart" class="crayons-avatar  crayons-avatar--l  "&gt;
            &lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F51323%2F32c15d3b-9f4f-4c25-ab65-4a5e55f33aab.jpg" alt="dimonsmart profile" class="crayons-avatar__image"&gt;
          &lt;/a&gt;
        &lt;/div&gt;
        &lt;div&gt;
          &lt;div&gt;
            &lt;a href="/dimonsmart" class="crayons-story__secondary fw-medium m:hidden"&gt;
              Dmitry Dorogoy
            &lt;/a&gt;
            &lt;div class="profile-preview-card relative mb-4 s:mb-0 fw-medium hidden m:inline-block"&gt;
              
                Dmitry Dorogoy
                
              
              &lt;div id="story-author-preview-content-2559519" class="profile-preview-card__content crayons-dropdown branded-7 p-4 pt-0"&gt;
                &lt;div class="gap-4 grid"&gt;
                  &lt;div class="-mt-4"&gt;
                    &lt;a href="/dimonsmart" class="flex"&gt;
                      &lt;span class="crayons-avatar crayons-avatar--xl mr-2 shrink-0"&gt;
                        &lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F51323%2F32c15d3b-9f4f-4c25-ab65-4a5e55f33aab.jpg" class="crayons-avatar__image" alt=""&gt;
                      &lt;/span&gt;
                      &lt;span class="crayons-link crayons-subtitle-2 mt-5"&gt;Dmitry Dorogoy&lt;/span&gt;
                    &lt;/a&gt;
                  &lt;/div&gt;
                  &lt;div class="print-hidden"&gt;
                    
                      Follow
                    
                  &lt;/div&gt;
                  &lt;div class="author-preview-metadata-container"&gt;&lt;/div&gt;
                &lt;/div&gt;
              &lt;/div&gt;
            &lt;/div&gt;

          &lt;/div&gt;
          &lt;a href="https://dev.to/dimonsmart/how-i-created-a-handy-mcp-server-in-c-to-retrieve-nuget-package-information-1gf5" class="crayons-story__tertiary fs-xs"&gt;&lt;time&gt;Jun 3 '25&lt;/time&gt;&lt;span class="time-ago-indicator-initial-placeholder"&gt;&lt;/span&gt;&lt;/a&gt;
        &lt;/div&gt;
      &lt;/div&gt;

    &lt;/div&gt;

    &lt;div class="crayons-story__indention"&gt;
      &lt;h2 class="crayons-story__title crayons-story__title-full_post"&gt;
        &lt;a href="https://dev.to/dimonsmart/how-i-created-a-handy-mcp-server-in-c-to-retrieve-nuget-package-information-1gf5" id="article-link-2559519"&gt;
          How I Created a Handy MCP Server in C# to Retrieve NuGet Package Information
        &lt;/a&gt;
      &lt;/h2&gt;
        &lt;div class="crayons-story__tags"&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/csharp"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;csharp&lt;/a&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/ai"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;ai&lt;/a&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/mcp"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;mcp&lt;/a&gt;
        &lt;/div&gt;
      &lt;div class="crayons-story__bottom"&gt;
        &lt;div class="crayons-story__details"&gt;
          &lt;a href="https://dev.to/dimonsmart/how-i-created-a-handy-mcp-server-in-c-to-retrieve-nuget-package-information-1gf5" class="crayons-btn crayons-btn--s crayons-btn--ghost crayons-btn--icon-left"&gt;
            &lt;div class="multiple_reactions_aggregate"&gt;
              &lt;span class="multiple_reactions_icons_container"&gt;
                  &lt;span class="crayons_icon_container"&gt;
                    &lt;img src="https://assets.dev.to/assets/sparkle-heart-5f9bee3767e18deb1bb725290cb151c25234768a0e9a2bd39370c382d02920cf.svg" width="18" height="18"&gt;
                  &lt;/span&gt;
              &lt;/span&gt;
              &lt;span class="aggregate_reactions_counter"&gt;4&lt;span class="hidden s:inline"&gt; reactions&lt;/span&gt;&lt;/span&gt;
            &lt;/div&gt;
          &lt;/a&gt;
            &lt;a href="https://dev.to/dimonsmart/how-i-created-a-handy-mcp-server-in-c-to-retrieve-nuget-package-information-1gf5#comments" class="crayons-btn crayons-btn--s crayons-btn--ghost crayons-btn--icon-left flex items-center"&gt;
              Comments


              3&lt;span class="hidden s:inline"&gt; comments&lt;/span&gt;
            &lt;/a&gt;
        &lt;/div&gt;
        &lt;div class="crayons-story__save"&gt;
          &lt;small class="crayons-story__tertiary fs-xs mr-2"&gt;
            8 min read
          &lt;/small&gt;
            
              &lt;span class="bm-initial"&gt;
                

              &lt;/span&gt;
              &lt;span class="bm-success"&gt;
                

              &lt;/span&gt;
            
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;/div&gt;


</description>
      <category>csharp</category>
      <category>ai</category>
      <category>mcp</category>
      <category>semantickernel</category>
    </item>
    <item>
      <title>How I Created a Handy MCP Server in C# to Retrieve NuGet Package Information</title>
      <dc:creator>Dmitry Dorogoy</dc:creator>
      <pubDate>Tue, 03 Jun 2025 17:53:49 +0000</pubDate>
      <link>https://forem.com/dimonsmart/how-i-created-a-handy-mcp-server-in-c-to-retrieve-nuget-package-information-1gf5</link>
      <guid>https://forem.com/dimonsmart/how-i-created-a-handy-mcp-server-in-c-to-retrieve-nuget-package-information-1gf5</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;User:&lt;/strong&gt; &lt;em&gt;What time is it right now?&lt;/em&gt;&lt;br&gt;
&lt;strong&gt;LLM:&lt;/strong&gt; &lt;em&gt;Um... I actually don't know. I have no idea what time it is.&lt;/em&gt;&lt;br&gt;
&lt;strong&gt;User:&lt;/strong&gt; &lt;em&gt;Okay, let's give you some tools.&lt;/em&gt; &lt;em&gt;(Clock, Compass and a thermometer)&lt;/em&gt;&lt;br&gt;
&lt;strong&gt;LLM:&lt;/strong&gt; &lt;em&gt;I think this clock can be useful. Where are the hands pointing?&lt;/em&gt;&lt;br&gt;
&lt;strong&gt;User:&lt;/strong&gt; &lt;em&gt;The small hand is at 9. The big hand is at 12. What time is it right now?&lt;/em&gt;&lt;br&gt;
&lt;strong&gt;LLM:&lt;/strong&gt; &lt;em&gt;Now I know the time. It is 9:00.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In this little analogy, the Large Language Model (LLM) couldn’t answer a simple question because it lacked &lt;strong&gt;external tools&lt;/strong&gt;. Only after the user provided a &lt;strong&gt;clock&lt;/strong&gt; (with maybe other tools) the LLM could get the current time and respond correctly. This story illustrates a key idea in modern AI assistants: &lt;strong&gt;function calling&lt;/strong&gt;, or letting an AI to use external functions/tools to get accurate information. In other words - "look out of the box"&lt;/p&gt;

&lt;h2&gt;
  
  
  Function Calling and why we Need the MCP protocol?
&lt;/h2&gt;

&lt;p&gt;The dialogue above is similar to how new AI assistants can use functions. Instead of guessing or making things up, the AI can call a tool (for example, a clock function) to get the real answer. This method is useful for many types of questions, from checking the time to reading files or calling APIs.&lt;/p&gt;

&lt;p&gt;However, to make this work in a consistent way across different tools and platforms, we need a standard protocol. This is where &lt;strong&gt;MCP&lt;/strong&gt; comes in. &lt;strong&gt;Model Context Protocol (MCP)&lt;/strong&gt; is an open standard that lets AI models interact with external tools and services through a unified interface. In simple terms, MCP defines how an AI (or its hosting environment) can discover what tools are available and call those tools with certain parameters, getting back results in a fixed format. Many IDEs and AI platforms (like VS Code’s GitHub Copilot agent mode) support MCP to enable AI-driven development helpers.&lt;/p&gt;

&lt;h2&gt;
  
  
  How MCP Works (A Quick Example)
&lt;/h2&gt;

&lt;p&gt;MCP messages are typically in JSON. Let’s revisit the clock scenario in technical terms. Suppose the user asks, “What time is it?” The AI, using MCP, would make a tool call request to an MCP server that has a clock tool:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"name"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"GetCurrentTime"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"parameters"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This JSON request means &lt;em&gt;“call the function named **GetCurrentTime&lt;/em&gt;* with no parameters.”* An MCP-compatible server that provides a clock tool would recognize this and return a result:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"result"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"2025-06-03T14:42:41Z"&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, the result is the current time in a standard format (ISO 8601 UTC). The AI can then use this result to answer the user’s question accurately.&lt;/p&gt;

&lt;p&gt;Now, consider a slightly different query: “What time is it in &lt;strong&gt;Madrid&lt;/strong&gt;?” If our clock tool allowed a location or timezone parameter, the interaction could look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"name"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"GetTime"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"parameters"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="nl"&gt;"timezone"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"Madrid"&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And the server might respond:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"result"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"2025-06-03T16:42:41+02:00"&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this hypothetical response, the time is adjusted for Madrid’s timezone (UTC+2). The key point is that MCP enables passing parameters to tools so the AI can get exactly the info it needs. The protocol handles listing available tools, invoking them, and returning results in a consistent JSON structure.&lt;/p&gt;

&lt;h2&gt;
  
  
  Hallucinations in Code Generation: A Real Problem
&lt;/h2&gt;

&lt;p&gt;So why did I bother creating a custom MCP server for NuGet packages? Because LLMs &lt;em&gt;hallucinate&lt;/em&gt; — especially when writing code. If you’ve ever used an AI coding assistant, you may have seen it confidently call functions that don’t exist or use the wrong parameters for a library. This tends to happen with APIs that the model wasn’t trained on or that have changed over time.&lt;/p&gt;

&lt;p&gt;For example, with NuGet packages (which are constantly evolving), an AI might:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Suggest &lt;strong&gt;outdated methods or interfaces&lt;/strong&gt; that were removed in newer versions&lt;/li&gt;
&lt;li&gt;Invent &lt;strong&gt;non-existent API calls&lt;/strong&gt; that “sound” plausible but aren’t real&lt;/li&gt;
&lt;li&gt;Mix up &lt;strong&gt;version differences&lt;/strong&gt;, using an API from a different version than the one you have&lt;/li&gt;
&lt;li&gt;Provide &lt;strong&gt;incomplete information&lt;/strong&gt;, missing important parameters or return details&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Such hallucinations can lead to code that doesn’t compile or bugs that are hard to trace. It wastes a developer’s time and erodes trust in the AI assistant.&lt;/p&gt;

&lt;h2&gt;
  
  
  A Solution: An MCP Server for NuGet Package Info
&lt;/h2&gt;

&lt;p&gt;To tackle this, I built &lt;strong&gt;DimonSmart.NugetMcpServer&lt;/strong&gt; – a small MCP server that gives AI assistants accurate, up-to-date information about NuGet package APIs. Instead of relying on the language model’s knowledge (which might be outdated or wrong), the AI can call my MCP server to &lt;strong&gt;get the real data straight from the NuGet package&lt;/strong&gt;. In other words, the AI asks the server about a package’s interfaces, methods or enums, and the server downloads the package (from nuget.org), inspects its assemblies, and returns the actual definitions. This greatly &lt;strong&gt;reduces hallucinations by providing precise API details from the source&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What does the NuGet MCP server do?&lt;/strong&gt; It currently focuses on interfaces and enums (for now. I'm going to extend). Key features include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Retrieve a &lt;strong&gt;specific interface’s definition&lt;/strong&gt; from a given package (including all its methods, properties, XML docs, etc.).&lt;/li&gt;
&lt;li&gt;List all &lt;strong&gt;interfaces in a package&lt;/strong&gt;, so you can discover what it offers.&lt;/li&gt;
&lt;li&gt;Retrieve an &lt;strong&gt;enum’s definition&lt;/strong&gt; from the package.&lt;/li&gt;
&lt;li&gt;Support specifying a &lt;strong&gt;version&lt;/strong&gt; of the package (or default to the latest) for version-specific info.&lt;/li&gt;
&lt;li&gt;Properly handle &lt;strong&gt;generic types&lt;/strong&gt; and format everything as valid C# code.&lt;/li&gt;
&lt;li&gt;Communicate via standard input/output (STDIO) using the MCP JSON protocol, which means it plugs into tools like VS Code easily.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In essence, it’s like a specialized “package inspector” tool that the AI can use whenever it needs authoritative info about a NuGet library’s API. No more guessing what methods &lt;code&gt;FooClient&lt;/code&gt; has or what properties interface &lt;code&gt;IBarService&lt;/code&gt; includes – the MCP server will tell the AI exactly what’s in the package.&lt;/p&gt;

&lt;h2&gt;
  
  
  How It’s Built (C# with MCP Library)
&lt;/h2&gt;

&lt;p&gt;I built an MCP server in C# and found it very easy, thanks to the &lt;code&gt;ModelContextProtocol.Server&lt;/code&gt; library (v0.2.0 preview). I follow the library’s rules to create tools. I write a C# method and add special attributes so it becomes an MCP tool. Then the server automatically finds these tools when it runs.&lt;/p&gt;

&lt;p&gt;For example, here’s a &lt;strong&gt;minimal tool&lt;/strong&gt; that I included for testing – it provides the current time (like our earlier clock analogy):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;McpServerToolType&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;TimeTool&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;McpServerTool&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;Description&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Returns the current server time in ISO 8601 format (YYYY-MM-DDThh:mm:ssZ)."&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nf"&gt;GetCurrentTime&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;DateTime&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;UtcNow&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;ToString&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"o"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This sample does the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;[McpServerToolType]&lt;/code&gt; attribute marks the class as a container for tool functions.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;[McpServerTool]&lt;/code&gt; attribute (on the method) exposes that method as an available tool to the MCP client, and the &lt;code&gt;Description&lt;/code&gt; provides a human-readable (LLM-Readable 😀) description of what it does.&lt;/li&gt;
&lt;li&gt;The method itself &lt;code&gt;GetCurrentTime()&lt;/code&gt; simply returns the server’s current time as a string. (Notice we format it as string in a standard way &lt;code&gt;"o"&lt;/code&gt; for ISO8601 UTC time).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When the MCP server runs, it will automatically find this tool and advertise it to clients. An AI could then invoke &lt;strong&gt;GetCurrentTime&lt;/strong&gt; just like in our earlier JSON example.&lt;/p&gt;

&lt;p&gt;Now, the NuGet-focused tools in &lt;strong&gt;NugetMcpServer&lt;/strong&gt; are built with the same pattern. They are just a bit more involved internally: they download the NuGet package, load the .dll, and extract the type info. Here are the main tools provided:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;ListInterfaces(packageId, version?)&lt;/code&gt; – Lists all public interfaces in the specified package (and version). This returns a list of interface names (and some metadata) so you know what’s available.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;GetInterfaceDefinition(packageId, interfaceName, version?)&lt;/code&gt; – Returns the full C# definition of a given interface from the package. You provide the package name and the interface you’re interested in, and it gives you the code (methods, properties, XML comments, etc.) as one big string result.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;GetEnumDefinition(packageId, enumName, version?)&lt;/code&gt; – Similarly, returns the complete definition of an enum type from the package.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Each of these is implemented as an MCP tool with the same attribute approach. For instance, &lt;code&gt;GetInterfaceDefinition&lt;/code&gt; is a method decorated with &lt;code&gt;[McpServerTool]&lt;/code&gt; and it returns a &lt;code&gt;string&lt;/code&gt; containing the interface’s code. Under the hood, it uses a helper service to format the interface nicely (with proper C# syntax) and ensure things like generic type parameters are rendered correctly.&lt;/p&gt;

&lt;p&gt;The server uses .NET’s Generic Host with an &lt;strong&gt;STDIO transport&lt;/strong&gt;, meaning it runs as a console app that reads JSON requests from stdin and writes JSON responses to stdout. This makes it easy to plug into VS Code or any other MCP client. The discovery of tools is automatic – thanks to the attributes, the &lt;code&gt;ModelContextProtocol&lt;/code&gt; library finds all tools and lists them for the client. So as soon as you run the server, a client can ask it “what tools do you have?” and it will respond with something like “GetInterfaceDefinition, ListInterfaces, GetEnumDefinition, GetCurrentTime,” along with their parameter schemas.&lt;/p&gt;

&lt;h2&gt;
  
  
  Installation and Usage in VS Code
&lt;/h2&gt;

&lt;p&gt;One of my goals was to make this tool &lt;strong&gt;easy to set up&lt;/strong&gt; and try out. I’m happy to say that &lt;strong&gt;NugetMcpServer is available on WinGet&lt;/strong&gt;, so Windows users can install it with a single command. For example, in a PowerShell or terminal, run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;winget &lt;span class="nb"&gt;install &lt;/span&gt;DimonSmart.NugetMcpServer
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will download and install the latest NugetMcpServer release. &lt;strong&gt;DimonSmart.NugetMcpServer&lt;/strong&gt; alias added automatically, so you can launch it from anywhere (no need to add .exe). By default it uses port-less STDIO, so you don’t have to worry about networking – it just sits and waits for JSON on stdin.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Using it in VS Code (Copilot Agent Mode):&lt;/strong&gt; If you have GitHub Copilot enabled with the new agent/chat mode, you can add this server as an MCP tool provider. The process is simple (and only needs to be done once): open your VS Code settings, search for “MCP”, and add a new MCP server configuration pointing to &lt;code&gt;NugetMcpServer&lt;/code&gt;. (VS Code’s official docs have a section on &lt;a href="https://code.visualstudio.com/docs/copilot/chat/mcp-servers" rel="noopener noreferrer"&gt;how to add MCP servers&lt;/a&gt; if you need guidance.) Once added, your AI assistant in VS Code can invoke the NuGet tools whenever it gets a related query. For example, if you ask in Copilot chat &lt;em&gt;“Show me what interfaces are in the Foo.Bar package”&lt;/em&gt;, Copilot can call &lt;code&gt;ListInterfaces&lt;/code&gt; from the server and give you a real answer instead of guessing.&lt;/p&gt;

&lt;p&gt;It’s worth noting that to my knowledge this project is &lt;strong&gt;one of the first precompiled MCP servers&lt;/strong&gt; readily available. Many existing MCP tool examples were scripts or needed building from source. By publishing on WinGet, I wanted to ensure anyone can quickly grab a ready-to-run server and immediately enhance their AI dev experience.&lt;/p&gt;

&lt;h2&gt;
  
  
  Future Plans and Feedback
&lt;/h2&gt;

&lt;p&gt;This project is still in progress. I have a lot of ideas to make AI-assisted development even smoother. For instance, I’m considering adding a feature to &lt;strong&gt;search for NuGet packages by description or keywords&lt;/strong&gt; – imagine asking the AI &lt;em&gt;“Is there a NuGet package for generating QR codes?”&lt;/em&gt; and the MCP server could suggest relevant packages by querying NuGet’s catalog. This could help with discovery of libraries, not just usage of known ones.&lt;/p&gt;

&lt;p&gt;I’d love to hear feedback, suggestions, or wild ideas from readers like you! Feel free to check out the project’s GitHub repo (linked below) – issues and pull requests are welcome.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Links:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;GitHub Repository:&lt;/strong&gt; &lt;a href="https://github.com/DimonSmart/NugetMcpServer" rel="noopener noreferrer"&gt;DimonSmart/NugetMcpServer&lt;/a&gt; – Source code, README, and issue tracker.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;My pet projects Live Demo:&lt;/strong&gt; &lt;a href="https://dimonsmart.github.io/Demo/" rel="noopener noreferrer"&gt;dimonsmart.github.io/Demo&lt;/a&gt; – Some of my pet projects in case you are interested.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;About Me:&lt;/strong&gt; &lt;a href="https://www.linkedin.com/in/dimonsmart/" rel="noopener noreferrer"&gt;LinkedIn – Dmitry Dorogoy&lt;/a&gt; – Let’s connect!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Finally, the project is open-source with a very permissive license. This means you can use it, integrate it, or modify it without worrying about restrictions. I hope this MCP server sparks some ideas and helps make your AI coding sessions more productive and less frustrating. Happy coding!&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>ai</category>
      <category>mcp</category>
    </item>
    <item>
      <title>Automatically Test Your Regex Without Writing a Single C# Line of Code</title>
      <dc:creator>Dmitry Dorogoy</dc:creator>
      <pubDate>Fri, 07 Jun 2024 20:41:18 +0000</pubDate>
      <link>https://forem.com/dimonsmart/automatically-test-your-regex-without-writing-a-single-c-line-of-code-1k9p</link>
      <guid>https://forem.com/dimonsmart/automatically-test-your-regex-without-writing-a-single-c-line-of-code-1k9p</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;If you've ever used regular expressions (regex), you know there's a saying: "Every problem can be solved with regex. But then you have one more problem."&lt;/p&gt;

&lt;p&gt;I hope readers can decide for themselves whether to use regular expressions. However, making sure your regex works correctly can be challenging.&lt;/p&gt;

&lt;p&gt;In many development teams, there's always someone who asks, "Have you written unit tests for this regex?"&lt;/p&gt;

&lt;p&gt;Developers often add comments above their regex with sample strings that should match or not match.&lt;/p&gt;

&lt;p&gt;Often, developers will add comments above their regex with sample strings that should match or not match. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Matches email addresses&lt;/span&gt;
&lt;span class="c1"&gt;// Example: "test@example.com"&lt;/span&gt;
&lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;emailRegex&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s"&gt;@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, there’s a hidden problem here: these comments can be misleading. A comment might claim a regex matches an example, but without actual testing, there's no guarantee.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Ideal Solution
&lt;/h2&gt;

&lt;p&gt;According to &lt;a href="https://en.wikipedia.org/wiki/TRIZ"&gt;TRIZ (Theory of Inventive Problem Solving)&lt;/a&gt;, the best solution is one where the system works effortlessly, without additional manual input. In our context, the perfect scenario would be a system that automatically tests your regex patterns without needing you to write explicit unit tests.&lt;/p&gt;

&lt;h2&gt;
  
  
  Presenting the Solution: DimonSmart.RegexUnitTester.TestAdapter
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;DimonSmart.RegexUnitTester.TestAdapter&lt;/code&gt; is here to save the day! This tool allows you to automatically check your regex patterns against provided samples using custom attributes. No more manual unit test writing or misleading comments—just straightforward and reliable regex testing.&lt;/p&gt;

&lt;h3&gt;
  
  
  How It Works
&lt;/h3&gt;

&lt;p&gt;This library leverages three main attributes to streamline regex testing:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;ShouldMatchAttribute&lt;/code&gt;&lt;/strong&gt;: This ensures that your regex correctly matches the expected data.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;ShouldNotMatchAttribute&lt;/code&gt;&lt;/strong&gt;: This confirms that your regex does not match unwanted data.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;InfoMatchAttribute&lt;/code&gt;&lt;/strong&gt;: This handles ambiguous cases, allowing further analysis without affecting the overall test outcome.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Code Samples
&lt;/h3&gt;

&lt;p&gt;Here are some examples of how to use these attributes in your code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nf"&gt;ShouldMatch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"test@example.com"&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt;
&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nf"&gt;ShouldNotMatch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"test@example"&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;const&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="n"&gt;EmailRegex&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s"&gt;@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nf"&gt;InfoMatch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"123-45-6789"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"SSN format"&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;const&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="n"&gt;SSNRegex&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s"&gt;@"^\d{3}-\d{2}-\d{4}$"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With these attributes, you can clearly define which strings should and shouldn’t match your regex patterns. The &lt;code&gt;InfoMatchAttribute&lt;/code&gt; is particularly useful for documenting ambiguous cases that need further review.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;By using &lt;code&gt;DimonSmart.RegexUnitTester.TestAdapter&lt;/code&gt;, you can ensure your regex patterns are accurate and reliable without the hassle of writing manual tests. Give it a try and see how it simplifies your development workflow.&lt;/p&gt;

&lt;p&gt;I'm the author of this library. If you have any questions or feedback, please don't hesitate to write me a few words about my library. Happy coding!&lt;/p&gt;




&lt;p&gt;You can find more details on installation and usage in the library’s &lt;a href="https://github.com/DimonSmart/RegexUnitTester"&gt;GITHUB&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>regex</category>
      <category>unittest</category>
      <category>csharp</category>
    </item>
    <item>
      <title>Stop Scattering .Trim(): Auto-trim All String Properties in C#</title>
      <dc:creator>Dmitry Dorogoy</dc:creator>
      <pubDate>Mon, 19 Dec 2022 08:06:54 +0000</pubDate>
      <link>https://forem.com/dimonsmart/trim-them-all-1mo0</link>
      <guid>https://forem.com/dimonsmart/trim-them-all-1mo0</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Once upon a time, I was diving into a new codebase and came upon an intriguing issue. StringTrim() calls polluted the entire codebase. I was taken aback. All user input, in my opinion, should be sanitized by calling at least the Trim function over all string properties. I discovered the problem root after digging a bit dipper. Users frequently copy and paste dates from local notebooks, communications, and so on. In addition, after selecting a string, it occasionally selects with surrounding space and newline characters.&lt;br&gt;
As a result, a simple UserName field could be filled all possible ways:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;"John Doe "&lt;/li&gt;
&lt;li&gt;" John Doe"&lt;/li&gt;
&lt;li&gt;" John Doe "&lt;/li&gt;
&lt;li&gt;"John Doe"&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Finally, separate program components treat this as if it were one or four different users. Simply because certain components clip spaces while others leave UserName alone.&lt;br&gt;
One amusing (actually not) outcome appears to be a success story: a man registered to the internet business twice (with space difference in the userName). However, the login component treats usernames with and without a leading space as one user. The same is true for the payment subsystem. However, the order handling component sees two distinct users. As a result, the user places one order, pays once, and receives it twice. :-)&lt;/p&gt;
&lt;h2&gt;
  
  
  Solve the problem with one smart enough nuget Package
&lt;/h2&gt;

&lt;p&gt;Soling this and similar situations as easy as pie. You should never trust user input and always remove leading and trailing spaces. Additionally it's a good practice to remove duplicate spaces inside the strings.&lt;/p&gt;

&lt;p&gt;Recommended nuget package is: &lt;a href="https://www.nuget.org/packages/DimonSmart.StringTrimmer/" rel="noopener noreferrer"&gt;StringTrimmer&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Usage is very simple. Just call TrimExtraSpaces() extension method over any user provided class. And this method automatically trim all public string properties.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;CreateUser&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;User&lt;/span&gt; &lt;span class="n"&gt;user&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="n"&gt;user&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;TrimExtraSpaces&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// Just one line&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;P.S. All string properties are found and trimmed using reflection in this nuget package. This method is better than nothing, but it is not the quickest! To increase class properties trimming speed I'm working on Source Generated StringTrimmmer code.&lt;br&gt;
&lt;a href="https://github.com/DimonSmart/StringTrimmerGenerator" rel="noopener noreferrer"&gt;StringTrimmerGenerator&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Feel free to conact me and contribute to the project to make user input safer to use.&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>dotnet</category>
    </item>
    <item>
      <title>Fun with C# Regex based Expression calculator</title>
      <dc:creator>Dmitry Dorogoy</dc:creator>
      <pubDate>Tue, 30 Mar 2021 03:17:47 +0000</pubDate>
      <link>https://forem.com/dimonsmart/fun-with-c-regex-based-expression-calculator-10mm</link>
      <guid>https://forem.com/dimonsmart/fun-with-c-regex-based-expression-calculator-10mm</guid>
      <description>&lt;p&gt;Hello dear readers!&lt;/p&gt;

&lt;p&gt;Once I was asked to write an expression calculator. And my first impulse was to write a classical calculator based on &lt;a href="https://en.wikipedia.org/wiki/Shunting-yard_algorithm"&gt;two stacks, also known as shunting yard algorithm&lt;/a&gt;. In this approach, one stack is used for values and the other for operators. It's a classical solution but I wanted to do something more interesting and inspiring and fun...&lt;/p&gt;

&lt;h2&gt;
  
  
  Intro
&lt;/h2&gt;

&lt;p&gt;We have a mathematical expression like: &lt;code&gt;2 + 2 * (2 + (2))&lt;/code&gt; and we need to calculate the result. There are some problems:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Resolving brackets&lt;/li&gt;
&lt;li&gt;Resolving operation priorities&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Let's do it with regular expressions!
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Bracket expander
&lt;/h3&gt;

&lt;p&gt;The regular expression could be easily used for finding some patterns in the string.&lt;br&gt;
The first simple patter is a pattern for expanding brackets:&lt;br&gt;
Like this: &lt;code&gt;\(\d+\)&lt;/code&gt;&lt;br&gt;
This pattern detects an open bracket followed by any number of digits and finally followed with a closed bracket.&lt;br&gt;
This simple regular expression is able to catch the expression: &lt;code&gt;(42)&lt;/code&gt;.&lt;br&gt;
But how could we extract the number and reject the brackets?&lt;br&gt;
Hopefully, the regular expressions have the ability to catch results into the named groups.&lt;br&gt;
Let's update our regex example: &lt;code&gt;\((?&amp;lt;number&amp;gt;\d+)\)&lt;/code&gt;&lt;br&gt;
With this regex, we could find numbers with brackets and take only a number.&lt;/p&gt;

&lt;h2&gt;
  
  
  Addition operation
&lt;/h2&gt;

&lt;p&gt;Let's check more complex operations. Addition.&lt;br&gt;
For adding two numbers we have to write a regular expression to find the number plus number. &lt;br&gt;
&lt;code&gt;(?&amp;lt;numberA&amp;gt;\d+)\+(?&amp;lt;numberB&amp;gt;\d+)&lt;/code&gt;&lt;br&gt;
Here we have two named capture groups and a "hardcoded" plus symbol.&lt;br&gt;
This expression allows us to detect expressions like &lt;code&gt;1+1&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Multiplication
&lt;/h2&gt;

&lt;p&gt;What's the difference between addition and multiplication? Actually only an operation. So, we use almost the same regular expression to detect multiplication. And the same for division and subtraction&lt;/p&gt;

&lt;h2&gt;
  
  
  Let's create an expression solver
&lt;/h2&gt;

&lt;p&gt;Let's assume we've got an expression &lt;code&gt;2*2+(2+2)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;At this moment we have got a bunch of regular expressions and small operation evaluators.&lt;br&gt;
In a simple way we've got regular expressions for:&lt;br&gt;
*( number ) =&amp;gt; number&lt;br&gt;
*numberA + numberB =&amp;gt; sum&lt;br&gt;
*numberA - numberB =&amp;gt; sub&lt;br&gt;
*numberA * numberB =&amp;gt; mul&lt;br&gt;
*numberA / numberB =&amp;gt; div&lt;/p&gt;

&lt;h3&gt;
  
  
  Step by step calculation
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;2*2+(2+2)&lt;/code&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;2*2&lt;/strong&gt;+(2+2)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;4&lt;/strong&gt;+(2+2)&lt;/li&gt;
&lt;li&gt;4+(&lt;strong&gt;2+2&lt;/strong&gt;)&lt;/li&gt;
&lt;li&gt;4+(&lt;strong&gt;4&lt;/strong&gt;)&lt;/li&gt;
&lt;li&gt;4+&lt;strong&gt;(4)&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;4+&lt;strong&gt;4&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;4+4&lt;/strong&gt; =&amp;gt; 8&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  How about priorities?
&lt;/h2&gt;

&lt;p&gt;It's a common question while we are talking about expression evaluators. &lt;br&gt;
And now we could use an interesting feature of regular expressions: &lt;a href="https://www.regular-expressions.info/lookaround.html"&gt;Negative lookahead&lt;/a&gt;.&lt;br&gt;
The main idea is to avoid matching num + num surrounding with high priority operators (* /).&lt;br&gt;
A bit simplified pattern:&lt;br&gt;
&lt;code&gt;(?![*/])(?&amp;lt;numberA&amp;gt;-?\d+\.?\d*)\+(?&amp;lt;numberB&amp;gt;-?\d+\.?\d*)(?![*/])&lt;/code&gt;&lt;br&gt;
Easy as pie. (c) Daddy Pig :-)&lt;/p&gt;

&lt;h2&gt;
  
  
  How to add constants?
&lt;/h2&gt;

&lt;p&gt;The most common constant is Pi., (3.14). In my solution, we could support constants in the same manner as the opening brackets.&lt;br&gt;
&lt;code&gt;(?i)PI&lt;/code&gt; The regular expression "?i" is a case insensitive switch.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to add math function support?
&lt;/h2&gt;

&lt;p&gt;What is the main difference between a constant Pi and, for example, Sinus function?&lt;br&gt;
Theis only one difference - brackets. And we should construct a regular expression to detect text like &lt;code&gt;Sin(number)&lt;/code&gt;.&lt;br&gt;
One important moment - we already have an open bracket function. And we also have a potentially conflicted Sin() function. And we have a simple way to solve this kind of problem - expression order!&lt;br&gt;
Let's check an example:&lt;code&gt;(Sin(Pi))+1&lt;/code&gt;&lt;br&gt;
To evaluate this function correctly we have to apply regexp substitutions in a particular order:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Replace Pi
(Sin(&lt;strong&gt;Pi&lt;/strong&gt;))+1 =&amp;gt; (Sin(&lt;strong&gt;3.14&lt;/strong&gt;))+1; Match: &lt;strong&gt;Pi&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;Calculate Sin(3.14)
(&lt;strong&gt;Sin(3.14)&lt;/strong&gt;)+1 =&amp;gt; (&lt;strong&gt;0.00&lt;/strong&gt;)+1; Match: &lt;strong&gt;Sin(3.14)&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;Open brackets
&lt;strong&gt;(0.00)&lt;/strong&gt;+1 =&amp;gt; &lt;strong&gt;0.00&lt;/strong&gt;+1; Match: &lt;strong&gt;(0.00)&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;Calculate Sum
&lt;strong&gt;0.00+1&lt;/strong&gt; =&amp;gt; &lt;strong&gt;1.00&lt;/strong&gt;; Match: &lt;strong&gt;0.00+1&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Additional possibilities
&lt;/h2&gt;

&lt;p&gt;I show only small examples with calculating only a simple math expression. Let imagine that our expression is a real DSL (Domain Specific Language) where Sin(x) is not a fast, but really time-consuming function. In this case, we could use the regular expressions ability to give us not only the first but all possible matches. For example, for function &lt;code&gt;Sin(0.5)+Sin(0.5)&lt;/code&gt; we detect two Sin function at once. As a result, we could use a parallel calculation.&lt;/p&gt;

&lt;h2&gt;
  
  
  Experiments!
&lt;/h2&gt;

&lt;p&gt;To continue my experiments, I wrote a classical two-stacks-based evaluator. After I created a random expression generator and run both calculators over the randomized expression until both could calculate expression without errors.&lt;/p&gt;

&lt;h3&gt;
  
  
  I got expected results:
&lt;/h3&gt;

&lt;p&gt;*( 7 * 6 ) * 2  = 84&lt;br&gt;
*4 ( - ( 5 ) )  = -1&lt;br&gt;
*3 * ( 8 ) * 8  = 192&lt;br&gt;
*7 + ( 1 - 8 ) * 9  = -56&lt;/p&gt;

&lt;p&gt;But! also a completely incorrect expression like this:&lt;br&gt;
*8 3 + - ( 9 )  = 2&lt;/p&gt;

&lt;p&gt;Regular expression based calculator allows us to see the whole evaluation path step by step:&lt;br&gt;
8 3 + - &lt;strong&gt;( 9 )&lt;/strong&gt; =&amp;gt; 8 3 + &lt;strong&gt;-9&lt;/strong&gt;; Match:  &lt;strong&gt;( 9 )&lt;/strong&gt;&lt;br&gt;
8 &lt;strong&gt;3 + -9&lt;/strong&gt; =&amp;gt; 8*&lt;em&gt;-6&lt;/em&gt;&lt;em&gt;; Match:  **3 + -9&lt;/em&gt;*&lt;br&gt;
&lt;strong&gt;8-6&lt;/strong&gt; =&amp;gt; &lt;strong&gt;2&lt;/strong&gt;; Match: &lt;strong&gt;8-6&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The classical two stacks algorithm interprets this expression as&lt;br&gt;
&lt;code&gt;(3+8)-9&lt;/code&gt; with the same result 2.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusions
&lt;/h2&gt;

&lt;p&gt;It's possible to create a simple calculator-like expression evaluator based on a regular expression. It's fun.&lt;br&gt;
&lt;a href="https://en.wikipedia.org/wiki/Shunting-yard_algorithm"&gt;Classical shunting yard algorithm&lt;/a&gt; could evaluate erroneous expressions.&lt;/p&gt;

&lt;h2&gt;
  
  
  Links
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://github.com/DimonSmart/FunWithCalculators"&gt;Fun with calculators github repository&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://en.wikipedia.org/wiki/Shunting-yard_algorithm"&gt;Shunting-yard algorithm&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://tomassetti.me/domain-specific-languages/"&gt;DSL&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;P.S. Feel free to comment/contact me if you like this work.&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>regex</category>
      <category>calculator</category>
      <category>expression</category>
    </item>
  </channel>
</rss>
