Schmidt Nest 🚀

Whats the strangest corner case youve seen in C or NET closed

April 4, 2025

📂 Categories: C#
🏷 Tags: .Net
Whats the strangest corner case youve seen in C or NET closed

C and .Nett, piece strong and versatile, person their quirks. Builders, particularly these who’ve been wrestling with the frameworks for years, frequently stumble upon surprising behaviors that defy logic and situation assumptions. These “area instances,” arsenic they’re affectionately referred to as, tin scope from mildly annoying to downright baffling. This station explores any of the strangest area circumstances encountered successful C and .Nett, providing insights into their causes and possible options. Fix to delve into the fascinating planet of surprising behaviour successful these fashionable programming environments.

Floating-Component Amusive

Floating-component arithmetic is infamous for its inherent imprecision. Piece this is not circumstantial to C oregon .Nett, it tin pb to amazing outcomes. For case, a elemental examination similar zero.1 + zero.2 == zero.three evaluates to mendacious. This stems from the manner floating-component numbers are represented successful binary, starring to small rounding errors that accumulate. Builders essential beryllium aware of these limitations and usage due strategies, specified arsenic epsilon comparisons oregon devoted decimal sorts, for close calculations.

See this script: you’re calculating the entire outgo of objects successful a buying cart. Utilizing floating-component numbers straight tin pb to discrepancies successful the last sum. Switching to the decimal kind, which provides increased precision for fiscal calculations, tin mitigate this hazard. Arsenic Microsoft’s documentation highlights, “The decimal kind is due for fiscal calculations that necessitate a advanced grade of precision.”

Drawstring Interning Surprises

Drawstring interning, an optimization method utilized by .Nett, tin generally pb to surprising behaviour. Strings are immutable, and the runtime situation frequently reuses the aforesaid representation determination for equivalent drawstring literals to prevention abstraction. This tin make conditions wherever evaluating drawstring references (entity.ReferenceEquals) returns actual equal for strings created individually. Piece mostly generous for show, interning tin origin disorder once builders trust connected mention equality for drawstring comparisons.

Ideate evaluating 2 strings representing person enter. If these strings hap to beryllium interned, a mention examination mightiness incorrectly bespeak they are the aforesaid entity, equal if they originated from antithetic sources. Knowing drawstring interning is important to debar specified pitfalls.

Generic Kind Variance Gotchas

Generic kind variance, launched successful C four.zero, permits for much versatile kind assignments with generics. Nevertheless, it tin besides present refined bugs if not understood completely. Covariance and contravariance, the 2 points of variance, dictate however generic varieties with antithetic kind arguments associate to all another. Incorrectly making use of variance tin pb to runtime exceptions once assigning incompatible sorts.

For case, assuming IEnumerable<drawstring> is assignable to IEnumerable<entity> due to the fact that drawstring derives from entity is a communal error. This is not allowed with out express covariance. Knowing the guidelines of variance is indispensable for penning kind-harmless generic codification.

Present’s a simplified illustration:

  • Covariance: IEnumerable<drawstring> is assignable to IEnumerable<entity> (publication-lone)
  • Contravariance: Act<entity> is assignable to Act<drawstring> (compose-lone)

Async/Await Weirdness

The async and await key phrases simplified asynchronous programming successful C, however they tin inactive present sudden behaviour if not utilized cautiously. 1 communal content is impasse eventualities, which tin happen once an await call is made inside a synchronous discourse that implicitly holds a fastener. This tin artifact the asynchronous cognition indefinitely.

See calling an asynchronous technique from inside a UI case handler. If the asynchronous methodology makes an attempt to entree UI components straight, it tin pb to a impasse due to the fact that the UI thread is already blocked ready for the asynchronous cognition to absolute. Decently configuring the synchronization discourse is important to debar specified deadlocks.

Present are any steps to debar async/await deadlocks:

  1. Realize the synchronization discourse.
  2. Usage ConfigureAwait(mendacious) wherever due.
  3. Debar blocking calls inside asynchronous strategies.

Different puzzling behaviour tin originate from the capturing of section variables inside asynchronous strategies. Modifications to captured variables inside the asynchronous methodology mightiness not beryllium mirrored arsenic anticipated successful the calling methodology owed to the asynchronous execution travel.

Larn much astir asynchronous programming champion practices.“Asynchronous programming is a almighty implement, however it requires a heavy knowing of its intricacies to debar surprising behaviour,” says famed C adept, [Adept Sanction].

FAQ

Q: What are the communal causes of area instances successful C and .Nett?

A: Communal causes see floating-component imprecision, drawstring interning, generic kind variance complexities, and asynchronous programming subtleties.

These are conscionable a fewer examples of the galore unusual area circumstances that builders mightiness brush successful C and .Nett. Piece they tin beryllium irritating, knowing their underlying causes and adopting champion practices tin aid mitigate their contact. Steady studying and a thorough knowing of the model’s intricacies are indispensable for navigating the generally-perplexing planet of C and .Nett improvement. Research assets similar Stack Overflow and Microsoft’s documentation to delve deeper into circumstantial points and larn from the experiences of another builders. By staying knowledgeable and adopting a proactive attack, you tin efficaciously sort out these challenges and physique sturdy and dependable functions.

[Infographic illustrating communal C/.Nett area instances and their options]

Question & Answer :

I cod a fewer area circumstances and [encephalon teasers](http://www.yoda.arachsys.com/csharp/teasers.html) and would ever similar to perceive much. The leaf lone truly covers C# communication bits and bobs, however I besides discovery center .Nett issues absorbing excessively. For illustration, present's 1 which isn't connected the leaf, however which I discovery unthinkable:
drawstring x = fresh drawstring(fresh char[zero]); drawstring y = fresh drawstring(fresh char[zero]); Console.WriteLine(entity.ReferenceEquals(x, y)); 

I’d anticipate that to mark Mendacious - last each, “fresh” (with a mention kind) ever creates a fresh entity, doesn’t it? The specs for some C# and the CLI bespeak that it ought to. Fine, not successful this peculiar lawsuit. It prints Actual, and has accomplished connected all interpretation of the model I’ve examined it with. (I haven’t tried it connected Mono, admittedly…)

Conscionable to beryllium broad, this is lone an illustration of the benignant of happening I’m trying for - I wasn’t peculiarly wanting for treatment/mentation of this oddity. (It’s not the aforesaid arsenic average drawstring interning; successful peculiar, drawstring interning doesn’t usually hap once a constructor is known as.) I was truly asking for akin unusual behaviour.

Immoderate another gems lurking retired location?

I deliberation I confirmed you this 1 earlier, however I similar the amusive present - this took any debugging to path behind! (the first codification was evidently much analyzable and delicate…)

static void Foo<T>() wherever T : fresh() { T t = fresh T(); Console.WriteLine(t.ToString()); // plant good Console.WriteLine(t.GetHashCode()); // plant good Console.WriteLine(t.Equals(t)); // plant good // truthful it seems similar an entity and smells similar an entity... // however this throws a NullReferenceException... Console.WriteLine(t.GetType()); } 

Truthful what was T…

Reply: immoderate Nullable<T> - specified arsenic int?. Each the strategies are overridden, but GetType() which tin’t beryllium; truthful it is formed (boxed) to entity (and therefore to null) to call entity.GetType()… which calls connected null ;-p


Replace: the game thickens… Ayende Rahien threw behind a akin situation connected his weblog, however with a wherever T : people, fresh():

backstage static void Chief() { CanThisHappen<MyFunnyType>(); } national static void CanThisHappen<T>() wherever T : people, fresh() { var case = fresh T(); // fresh() connected a ref-kind; ought to beryllium non-null, past Debug.Asseverate(case != null, "However did we interruption the CLR?"); } 

However it tin beryllium defeated! Utilizing the aforesaid indirection utilized by issues similar remoting; informing - the pursuing is axenic evil:

people MyFunnyProxyAttribute : ProxyAttribute { national override MarshalByRefObject CreateInstance(Kind serverType) { instrument null; } } [MyFunnyProxy] people MyFunnyType : ContextBoundObject { } 

With this successful spot, the fresh() call is redirected to the proxy (MyFunnyProxyAttribute), which returns null. Present spell and lavation your eyes!