🚀 C# 15 Just Changed How We Handle Multiple Types! The wait is finally over. Microsoft just dropped Union Types in .NET 11 Preview 2, and this is one of the most-requested C# features we've ever seen. What are Union Types? Think about this: You have a value that could be a string, int, or DateTime. Before, you had to: - Use object and cast manually - Return tuples with IsValid flags - Create wrapper classes - Hope the runtime doesn't surprise you Now you can simply write: ValueWithUnion<string | int | DateTime> value = GetData(); And let the compiler ensure you handle all cases. No casting. No runtime surprises. Why This Matters ✅ Compile-time exhaustiveness - Missing a case? That's a compile error. ✅ Zero-cost performance - Stored just like regular types. ✅ Self-documenting code - The type signature tells the story. ✅ Type-safe patterns - No more object casting nightmares. Real-World Example: Before: object result = GetValue(); if (result is string str) { ... } else if (result is int num) { ... } Now: var result = GetValue(); // returns string | int switch (result) { case string str: ... case int num: ... } Simple. Clean. Correct. Practical Use Cases: 📌 API response handling (success/error/redirect) 📌 Validation results (error code, message, or detailed errors) 📌 Cache values that could be any type 📌 Command patterns with multiple failure modes Try It Today: Union Types are in .NET 11 Preview 2. Get the SDK here: https://lnkd.in/eseijNqc Requires Visual Studio 2026 Insider or later. What Do You Think? I've been testing this for a few weeks and it's already changed how I write code. Type handling feels... natural again. What's been your biggest pain point with type handling in C#? Drop your thoughts below! 👇 💬 Have questions about the implementation? Ask me in the comments. Read the full article: https://lnkd.in/eKv2Naju Connect on LinkedIn: https://lnkd.in/eAHKnx84 Portfolio: https://lnkd.in/ekRNczNQ #DOTNET #CSharp #Programming #SoftwareDevelopment #TechInnovations #Coding #DevCommunity #CSharp15 #DotNet11 #CleanCode
C# 15 Union Types Simplify Type Handling
More Relevant Posts
-
🚀 C# 11.0 (2022) – Power, Performance & Precision Released with .NET 7, C# 11.0 takes modern development to the next level with features focused on performance, safety, and developer productivity. Here’s a complete breakdown of all key features 👇 ✨ 1. Raw String Literals (""""") Write multi-line strings without escape characters. → Perfect for JSON, SQL, and HTML. ✨ 2. Required Members Force initialization of important properties. → Ensures objects are always valid. ✨ 3. Generic Math Perform mathematical operations on generic types. → Write reusable, high-performance numeric code. ✨ 4. Auto-Default Structs Structs now automatically initialize fields to default values. ✨ 5. File-Scoped Types Define types without wrapping them inside namespaces. ✨ 6. List Patterns Pattern match arrays and lists more easily. → Cleaner and more expressive conditions. ✨ 7. UTF-8 String Literals Create UTF-8 strings at compile time for better performance. ✨ 8. Pattern Matching Enhancements Even more powerful and readable pattern matching capabilities. ✨ 9. Lambda Improvements Add attributes to lambda parameters → more flexibility. ✨ 10. Interpolated String Handler Improvements Better performance and control for string formatting (especially logging). ✨ Other Notable Improvements • Better overload resolution • Improved method group conversions • Enhanced compiler warnings & analyzers • Performance improvements in JIT & runtime 💡 Why C# 11.0 Matters? ✔ Boosts performance (generic math, UTF-8 strings) ✔ Improves code safety (required members) ✔ Makes code cleaner and more expressive ✔ Designed for modern, scalable applications 📌 C# 11.0 is all about writing less code with more power and control. 👉 Which feature are you excited to try? #CSharp #DotNet #CSharp11 #Programming #Developers #Coding #SoftwareEngineering #Tech #LearnToCode #VisualStudio
To view or add a comment, sign in
-
-
🚀 Threads vs Tasks in .NET — Stop Writing Complex Multithreading Code! Multithreading is powerful… but also tricky 😵💫 In .NET, we have two ways to achieve it: 👉 Thread 👉 Task Both are used for the same purpose — doing work in parallel (multithreading). But here’s the real difference 👇 🔍 Thread vs Task (Simple Explanation) 🧵 Thread Low-level concept Available in almost all languages (Java, C#, etc.) Requires manual handling More control, but more complexity ⚡ Task High-level abstraction introduced by Microsoft Built on top of threads Easier, cleaner, and more powerful Here is why Tasks (TPL) win every time: ✅ Resource Efficiency: Tasks use the Thread Pool. They don't create a new OS thread every time, saving massive memory. ✅ Chaining: .ContinueWith() or await makes sequence logic look like a story, not a callback nightmare. ✅ Exception Handling: Try catching an exception in a manual thread. It's messy. Tasks bubble them up naturally. 👉 The Simple Rule: 🚲 Thread (Cycle )= Manual control, high effort, slow setup. 🏍️ Task (Motorcycle )= Optimized, high speed, managed by the runtime. Check out my breakdown below! 👇 Both will take you to the destination… But one is faster, smoother, and easier to ride 😉 💡 Why Tasks are Better than Threads? 🔥 1. Simplified Code No need to manually start threads Cleaner and more readable code 🔥 2. Easy Exception Handling Built-in support No messy try-catch across threads 🔥 3. Return Values Tasks can return results (Task<T>) Threads don’t support this easily 🔥 4. Task Chaining Run tasks one after another Use .ContinueWith() or async/await 🔥 5. Parent-Child Relationships Easily manage multiple tasks together 🔥 6. Better Performance Handling Thread pooling handled internally Optimized by .NET runtime 🧠 Key Takeaway 👉 Threads are the core building blocks 👉 Tasks are the smart way to use them Instead of writing complex multithreading logic: ✅ Use Task ❌ Avoid manual thread management (unless really needed) #DotNet #CSharp #Multithreading #Task #Thread #AsyncAwait #SoftwareDevelopment #Programming #BackendDevelopment #DotNetCore #Developers #Coding #Tech #LearnToCode #CleanCode #ProgrammingTips #DeveloperCommunity #SoftwareEngineer #CodeNewbie #TechLearning
To view or add a comment, sign in
-
-
Most developers only use 5% of what LINQ can actually do. I was one of them for years. Then I discovered these 5 underused methods that completely changed how I write C# code. No more messy loops. No more workarounds. Just clean, expressive logic that reads like plain English. Here is what you are probably missing: 1. Zip You have two separate lists of related data. Instead of writing a for loop with an index just to pair them together, Zip does it in one line. It combines both sequences element by element, perfectly paired, perfectly readable. 2. Chunk Need to process data in batches? Paginate results? Before Chunk existed, developers wrote entire custom extension methods just for this. Now it is built in. Pass a size, get groups. Done. 3. OfType<T> Working with a mixed collection of objects? OfType filters by type AND casts safely, all in one step. No null checks. No invalid cast exceptions. Just the items you actually want. 4. DistinctBy Stop reaching for GroupBy just to remove duplicates based on a single property. DistinctBy does exactly that, in one clean method call. It is the tool that should have existed years ago. 5. SelectMany If your data is nested, SelectMany flattens it. A list of orders, each with multiple items? One line and you have every item in a single flat sequence. No nested loops required. And if those were not enough, here are 5 bonus methods that almost made the list: SequenceEqual for comparing collections. Aggregate for custom accumulation logic. GroupJoin for advanced grouping like a left join. ToLookup for fast read-only grouping. Intersect for finding common elements between two collections. The real lesson here is this. LINQ is not about writing less code. It is about writing code that communicates clearly. When someone reads your logic and instantly understands what it does without tracing through a loop, that is clean engineering. The more LINQ you learn, the cleaner your thinking becomes. And that carries over into everything you build. Which one of these did you not know about before today? Drop it in the comments. 🔔 Follow Bilal Ahmad for more .NET, C#, and Clean Architecture tips! #CSharp #DotNet #LINQ #Programming #SoftwareDevelopment #CleanCode #BackendDevelopment #CodeQuality #SoftwareEngineering #Developer #100DaysOfCode #TechTips #CodingTips #MicrosoftDeveloper #DevCommunity #CodeNewbie #ProgrammingTips #LearnToCode #TechLinkedIn #DotNetDeveloper
To view or add a comment, sign in
-
-
Most .NET developers use async/await daily, but how many consider the "hidden cost" under the hood? 💡 When you mark a method as async, the C# compiler doesn't just run it as is. It completely rewrites your method, generating a complex State Machine (IAsyncStateMachine). To preserve your local variables across await boundaries when the thread is released back to the Thread Pool, those variables are hoisted from the Stack and boxed onto the Heap. The result? Every asynchronous call that actually yields execution creates a memory allocation, adding continuous pressure to the Garbage Collector. 🛠️ The Optimization: If you have a method that frequently completes synchronously (e.g., returning data from a memory Cache), return a ValueTask<T> instead of Task<T>. Because ValueTask is a struct (Value Type), it remains on the Stack during synchronous completion—guaranteeing Zero Allocation. ⚠️ A crucial architectural reminder: Never use async void (except for UI event handlers). It’s a dangerous "fire-and-forget" trap. Unhandled exceptions inside an async void method bypass the calling try-catch blocks and will crash your entire application process. Mastering asynchronous programming is about more than just preventing thread blocking—it's about strict resource efficiency and memory management. What’s the most interesting performance optimization you’ve applied in your .NET applications? Let's discuss in the comments! 👇 #dotnet #csharp #softwareengineering #performance #backend #dotnetcore #architecture #coding
To view or add a comment, sign in
-
𝗦𝗧𝗢𝗣 𝗪𝗥𝗜𝗧𝗜𝗡𝗚 𝟮𝟬-𝗣𝗔𝗥𝗔𝗠𝗘𝗧𝗘𝗥 𝗖𝗢𝗡𝗦𝗧𝗥𝗨𝗖𝗧𝗢𝗥𝗦. 🛑 If you’re still building massive constructors just to ensure your objects aren't "hollow" or invalid, you’re stuck in a boilerplate nightmare. It's time to move to modern C#. Let’s talk about a feature that finally fixed the "Incomplete Object" problem: 𝗿𝗲𝗾𝘂𝗶𝗿𝗲𝗱 members. 𝗧𝗛𝗘 𝗣𝗥𝗢𝗕𝗟𝗘𝗠: 𝗧𝗛𝗘 𝗖𝗢𝗡𝗦𝗧𝗥𝗨𝗖𝗧𝗢𝗥 𝗧𝗥𝗔𝗣 In the old days, you had two bad choices: Constructors: Great for safety, but they become a mess of parameters that are hard to read and maintain. Object Initializers: Look beautiful (new User { Name = "K" }), but they don't force the developer to set anything. You end up with NullReferenceExceptions because someone forgot a field. You were choosing between safety and syntax. 𝗧𝗛𝗘 𝗦𝗢𝗟𝗨𝗧𝗜𝗢𝗡: 𝗧𝗛𝗘 𝗿𝗲𝗾𝘂𝗶𝗿𝗲𝗱 𝗞𝗘𝗬𝗪𝗢𝗥𝗗 Introduced in C# 11, the required modifier gives you the best of both worlds. You get the clean look of object initializers with the "iron-clad" safety of a constructor. 𝗧𝗛𝗘 𝗖𝗢𝗗𝗘: public class User { // The compiler will THROW an error if this isn't set during initialization public required string Email { get; init; } public required string Username { get; init; } public DateTime JoinedDate { get; init; } = DateTime.UtcNow; } // ✅ This works perfectly var user1 = new User { Email = "hello@example.com", Username = "DevGuru" }; // ❌ This won't even COMPILE var user2 = new User { Email = "missing_username@example.com" }; 𝗪𝗛𝗬 𝗧𝗛𝗜𝗦 𝗜𝗦 𝗔 𝗪𝗜𝗡: Compile-Time Safety: If a dev adds a new "required" property to a class, every piece of code that creates that object will break immediately—preventing runtime bugs before they happen. Zero Boilerplate: No more mapping 15 parameters from a constructor to private fields. Readability: Object initializers are much easier to scan than a long list of constructor arguments where you can't tell which string is "FirstName" and which is "LastName." 𝗧𝗛𝗜𝗡𝗞𝗜𝗡𝗚 𝗢𝗨𝗧𝗦𝗜𝗗𝗘 𝗧𝗛𝗘 𝗕𝗢𝗫 📦 Combine required with init properties. This creates Immutable, Mandatory Data Structures. You ensure the data is there when created, and you guarantee it can't be changed accidentally later. It’s the ultimate "defensive programming" move. 𝗧𝗛𝗘 𝗧𝗔𝗞𝗘𝗔𝗪𝗔𝗬: Stop doing the manual labor of checking for nulls or writing endless constructor overloads. Use required to let the compiler be your bodyguard. #CSharp #DotNet #CleanCode #ProgrammingTips #SoftwareArchitecture #CodingLife #Innovation
To view or add a comment, sign in
-
C#/.NET Performance Tip — String Concatenation in Loops Many .NET developers still use += inside loops without realizing how expensive it really is. Using result += "x" inside a 1,000-iteration loop is 100 times slower than using StringBuilder.Append. When += is used on a string, .NET must: - Allocate a brand new string on every single iteration - Copy all existing characters into the new buffer - Discard the old string for the garbage collector In contrast, when StringBuilder is used, .NET: - Maintains one internal, growable buffer - Appends characters in place with zero extra allocations - Converts to a string only once at the end This pattern applies anywhere you build text dynamically: - Logging and reporting - CSV / JSON generation - Query construction - Any loop-based text assembly A small change can lead to a massive impact at scale. Benchmark results show: 4.21 us (StringBuilder) vs 412.50 us (+=), with 2.1 KB vs 2,500 KB allocated. Pre-size your StringBuilder when you know the capacity — even better. #csharp #dotnet #performance #programming #tips #coding #softwaredevelopment #aspnetcore #developer #cleancode
To view or add a comment, sign in
-
-
🚀 C# 10.0 (2021) – Less Boilerplate, More Productivity Released with .NET 6, C# 10.0 focused on making your code cleaner, simpler, and more efficient—with small changes that deliver big impact. Here’s a complete breakdown of all key features 👇 ✨ 1. Global Using Directives Declare "using" statements once for the entire project. → No more repeating imports in every file. ✨ 2. File-Scoped Namespaces Write namespaces in a single line. → Reduces indentation and improves readability. ✨ 3. Record Structs Combine value types with record features (immutability + value equality). ✨ 4. Improved Record Types Records now support inheritance and more flexibility. ✨ 5. Const Interpolated Strings Use string interpolation in "const" declarations. ✨ 6. Extended Property Patterns More powerful pattern matching with nested properties. ✨ 7. Lambda Improvements Better type inference + ability to add attributes to lambdas. ✨ 8. "var" in More Places Use "var" in lambda parameters and other scenarios. ✨ 9. Better Nullability Analysis Improved compile-time checks for safer null handling. ✨ 10. Parameterless Struct Constructors Initialize structs with default constructors. ✨ Other Notable Improvements • Implicit global usings in .NET 6 • Performance improvements (JIT & runtime) • Better diagnostics and error messages • Improved async and compiler behavior 💡 Why C# 10.0 Matters? ✔ Reduces repetitive code (global usings) ✔ Improves readability (file-scoped namespaces) ✔ Enhances performance and safety ✔ Makes modern C# even more developer-friendly 📌 Small features, but huge productivity gains for real-world projects. 👉 Which feature made your coding easier? #CSharp #DotNet #CSharp10 #Programming #Developers #Coding #SoftwareEngineering #Tech #LearnToCode #VisualStudio
To view or add a comment, sign in
-
-
Hello, C++ developers. [Post 33] ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ TOPIC: std::thread Basics - Creating and Managing Threads Building blocks of concurrent C++ programming What this carousel covers: → std::thread fundamentals: immediate execution on construction, thread starts instantly when object is created → Thread lifecycle and critical join/detach requirement: destructor calls std::terminate() if neither is called → Thread states and joinability: default-constructed, active, joined, detached, and moved-from states → Argument passing with std::ref: parameters are copied by default, must use std::ref() for true reference semantics → Callable types support: function pointers, lambdas, functors, and member functions as thread entry points → Move-only semantics: deleted copy constructor enforces unique ownership, prevents multiple objects owning same thread → Thread IDs and hardware_concurrency(): opaque identifiers and querying available CPU cores → Detached thread dangers: capturing stack variables by reference leads to dangling references and crashes → Platform abstraction: portable interface wrapping pthreads (Linux) and Win32 threads (Windows) Key insights: ◆ Thread lifecycle rule: MUST call join() or detach() before destruction, otherwise std::terminate() aborts the entire program—this design forces explicit lifetime management ◆ Arguments are copied by default to prevent dangling references: use std::ref() when you need true reference semantics and can guarantee lifetime safety ◆ Join vs detach: join() blocks until thread completes (for synchronization), detach() runs independently (for fire-and-forget background tasks) ◆ Double join/detach causes undefined behavior: once joined or detached, thread becomes non-joinable, always check joinable() before operations ◆ Detached threads must be self-contained: never capture stack variables by reference, they may outlive the creating scope—use capture by value or shared_ptr ◆ Thread creation overhead (1-10ms): for short-lived tasks, creation cost dominates execution time—prefer thread pools for performance-critical code ◆ Exceptions don't cross thread boundaries: uncaught exceptions call std::terminate(), must use std::exception_ptr to manually propagate between threads ◆ Real-world example: autonomous vehicles require parallel processing (perception at 30Hz, localization at 100Hz, planning at 10Hz) with deterministic timing and thread pools ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Note: LinkedIn compresses carousel images. For best experience, download the PDF or pinch-zoom on mobile. #CPlusPlus #CPP #Multithreading #StdThread #Concurrency #ParallelProgramming #ModernCPP #Programming #SoftwareEngineering #TechEducation #DeveloperLife #BestPractices #TechnicalExcellence
To view or add a comment, sign in
-
🚧 C# 15 (Preview) — Union Types Union Type means: 👉 a variable can be one of a fixed set of types (not anything else) 👉 unlike inheritance, it’s a closed set — no one can extend it later 👉 and the compiler forces you to handle every possible case 💡 Example: public record Success<T>(T Data); public record ValidationError(string Message); public record SystemError(string Message); public union Result<T>(Success<T>, ValidationError, SystemError); 👉 Here Result<T> can only be: ➖ Success<T> ➖ ValidationError ➖ SystemError Nothing else ❗ 🧠 Service public class UserService { public Result<UserDto> GetUser(int id) { if (id <= 0) return new ValidationError("Invalid Id"); try { var user = new UserDto(id, "Mofaggol"); if (user is null) return new SystemError("User not found"); return new Success<UserDto>(user); } catch (Exception ex) { return new SystemError(ex.Message); } } } 🌐 Controller [HttpGet("{id}")] public IActionResult Get(int id) { var result = _userService.GetUser(id); return result switch { Success<UserDto> s => Ok(s.Data), ValidationError ve => BadRequest(new { error = ve.Message }), SystemError se => StatusCode(500, new { error = se.Message }) }; } ⚖️ Old vs New (short) ➖ ❌ Old approach: ➖ bool + message ➖ object ➖ exceptions for flow 👉 Not type-safe, easy to miss cases ✅ Union Type: ➖ fixed outcomes ➖ compile-time safety ➖ clean and predictable API 👉 One line: Union Types make your API responses explicit, type-safe, and compiler-enforced 🚀 Read more: https://lnkd.in/dcw33DPc Repo: https://lnkd.in/dfMm5CeY #dotnet #csharp #csharp15 #dotnetdev #aspnetcore #webapi #backend #softwareengineering #programming #cleanarchitecture #ddd #designpatterns #api #restapi #microservices #developer #coding #tech #softwaredeveloper #learncoding #100daysofcode #devcommunity #cloud #azure #fullstack #oop #bestpractices #architecture #codinglife
To view or add a comment, sign in
-
.NET 11 Preview 3 is available! https://lnkd.in/eHha_-T5 All my .NET 10 books can be used with .NET 11. Read how at the following link: https://lnkd.in/e9yGSqGC What do I plan to cover in the 11th edition of my book, C# 15 and .NET 11 - Modern Cross-Platform Development Fundamentals, planned to publish on November 10, 2026? Any new features that are useful for beginner-to-intermediate developers. For example: -> C# 15 - Collection expression arguments - Compiler support for union types was added in Preview 2. Preview 3 includes better IDE support for working with union types: https://lnkd.in/eyxS6NjH -> .NET 11 SDK and Runtime - File-based apps can be split across files using #:include - dotnet run -e passes environment variables from the command line - dotnet run: Interactive target framework and device selection powered by Spectre.Console - Runtime-native async - Solution filters can now be edited from the CLI -> .NET 11 libraries - Native Zstandard (zstd) compression support - HTTP automatic decompression with Zstandard - BFloat16 floating-point type - ZipArchiveEntry improvements - Tar Archive format selection - FrozenDictionary collection expression support - Rune support in String, StringBuilder, and TextWriter - MediaTypeMap for MIME type lookups - Hard Link creation APIs - DivisionRounding for integer division modes - Generic GetTypeInfo for System.Text.Json -> EF Core 11 - Requires .NET 11 SDK to build and .NET 11 runtime to run - Support for LINQ MaxBy and MinBy - Discriminated union type support -> ASP.NET Core 11 - .NET Web Worker project template - TempData support for Blazor - OpenAPI 3.2.0 support - Label, DisplayName, and BasePath components for Blazor forms - MathML namespace support - Discriminated union type support in Minimal API web services For each book, you can get a Central Package Management file with updated package versions from the following links: C# 14 and .NET 10 - Modern Cross-Platform Development Fundamentals https://lnkd.in/ezS8F-Wt Apps and Services with .NET 10 https://lnkd.in/eK-GEV9B Real-World Web Development with .NET 10 https://lnkd.in/eV2bks-g Tools and Skills for .NET 10 https://lnkd.in/eBxaam_N Visual Studio 2026 is also now updated monthly so be sure to run the Visual Studio Installer to get your installation(s) up-to-date. #dotnet #dotnet11 #net11 #visualstudio
To view or add a comment, sign in
-
More from this author
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development