Tag: csharp
All the articles with the tag "csharp".
-
Device Bound Session Credentials in ASP.NET Core
A session cookie is a bearer token, which is a polite way of saying that whoever holds it is you. Copy the cookie, replay it from another machine, and the server happily serves your account. Nothing about the request proves which device it came from, so a cookie lifted by malware, an XSS payload, or a stray database backup keeps working until it expires. For a long-lived session, that can be weeks.
-
Keyed Services (Named registrations) in .NET Service Provider
You have an IMessageSender interface, with two implementations: EmailMessageSender and SmsMessageSender. You register both, and now the question is which one gets injected into your OrderConfirmationService constructor. The answer, unhelpfully, is whichever was registered last. This may also introduce subtle, unexpected bugs when new services are registered.
-
TimeProvider and the End of Untestable DateTime.Now
DateTime.Now is one of those calls that looks harmless until you try to write a test around it. It’s a static property that reads the system clock, and there’s no way to control what it returns without wrapping it in something injectable. I have wrapped it in codebases, and others have too. Unfortunately, everyone wrapped it their way. Since .NET 8, we can all stop reinventing the same abstraction and use TimeProvider instead.
-
Discriminated unions in C# and .NET 11 (for real this time)
Back in 2023, I wrote about discriminated unions in C# and how C# developers had to work around the lack of language support using things like ASP.NET Core’s Results<> type or the OneOf NuGet package. Real C# language support (csharplang issue #113) had been open for years with no sign of a proper solution. Well, the wait is over. C# 15, shipping with .NET 11 (preview), introduces first-class union types. Let’s have a look.
-
Provide opt-in to experimental APIs using C#12 ExperimentalAttribute
When writing libraries and frameworks that others are using, it’s sometimes hard to convey that a given API is still considered “experimental”. For example, you may want to iterate on how to work with part of the code base with the freedom to break things, while still allowing others to consume that code if they are okay with that.
-
Discriminated Unions in C#
Discriminated unions have been a long-standing request for C#. While F# users have had discriminated unions for years, C# developers will have to wait a bit longer. What discriminated unions allow you to do is tell the compiler (and other tooling like your IDE) that data can be one of a range of pre-defined types.