C# 14 Is Here: Everything You Need to Know (With Code Examples)

Microsoft has shipped C# 14 alongside .NET 10, and it’s packed with quality-of-life improvements that make everyday code cleaner, safer, and more expressive. Let’s walk through every major feature — with fresh, practical examples you can try right now.


1. Extension Members — Properties, Statics, and Operators on Any Type

C# has long supported extension methods. C# 14 takes it much further with the new extension block — you can now add properties, static members, and even operators to types you don’t own.

Imagine you work with strings a lot and want a clean .IsValidEmail check, a .WordCount property, and the ability to repeat a string with *:

public static class StringExtensions
{
extension(string text)
{
// Extension property — use it like: email.IsValidEmail
public bool IsValidEmail => text.Contains('@') && text.Contains('.');
// Extension property — use it like: sentence.WordCount
public int WordCount => text.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length;
}
extension(string)
{
// Static extension property — use it like: string.Placeholder
public static string Placeholder => "N/A";
// User-defined operator — use it like: "hello" * 3 => "hellohellohello"
public static string operator *(string text, int times) =>
string.Concat(Enumerable.Repeat(text, times));
}
}
// Usage:
string email = "dev@example.com";
Console.WriteLine(email.IsValidEmail); // True
Console.WriteLine("hello world".WordCount); // 2
Console.WriteLine(string.Placeholder); // N/A
Console.WriteLine("ping! " * 3); // ping! ping! ping!

This is a game-changer for library authors — your APIs can now feel like true language primitives.


2. The field Keyword — Say Goodbye to Backing Fields

Every C# developer has written a property with validation that forced them to declare a private backing field. The new field keyword lets the compiler generate it for you.

Here’s a UserProfile class that enforces age and username rules — no manual backing fields needed:

public class UserProfile
{
// Compiler synthesizes the backing field automatically
public string Username
{
get;
set => field = string.IsNullOrWhiteSpace(value)
? throw new ArgumentException("Username cannot be blank.")
: value.Trim().ToLower();
}
public int Age
{
get;
set => field = (value is < 0 or > 150)
? throw new ArgumentOutOfRangeException(nameof(Age), "Age must be between 0 and 150.")
: value;
}
}
// Usage:
var profile = new UserProfile();
profile.Username = " Alice "; // stored as "alice"
profile.Age = 30; // fine
profile.Age = 200; // throws ArgumentOutOfRangeException

Cleaner classes, less noise — and full control over validation logic without the ceremony.


3. Null-Conditional Assignment — Assign Only When It Makes Sense

The ?. operator has been a null-safety staple for reading values. In C# 14, you can use it on the left side of an assignment too — so the right side only executes when the target isn’t null.

Consider an e-commerce scenario where you conditionally update a shopping cart:

public class Cart
{
public string PromoCode { get; set; }
public List<string> Items { get; set; } = new();
public decimal Discount { get; set; }
}
Cart activeCart = GetActiveCart(); // might return null
// Old way — manual null guard required:
if (activeCart != null)
{
activeCart.PromoCode = "SAVE20";
activeCart.Discount += 20m;
}
// C# 14 — clean and concise:
activeCart?.PromoCode = "SAVE20";
activeCart?.Discount += 20m; // compound assignment works too!
// The promo code lookup won't even run if activeCart is null:
activeCart?.PromoCode = FetchBestPromoFromApi();

Notice the last line — FetchBestPromoFromApi() is not called at all if activeCart is null. That’s a real benefit when those calls are expensive.


4. Implicit Span Conversions — High-Performance Code, Less Friction

Span<T> and ReadOnlySpan<T> are the go-to tools for zero-allocation data processing in .NET. C# 14 introduces implicit conversions so you can pass arrays where spans are expected — and vice versa — without manual casting.

// A method that processes data efficiently using ReadOnlySpan
static double AverageTemperature(ReadOnlySpan<double> readings)
{
double sum = 0;
foreach (var temp in readings) sum += temp;
return sum / readings.Length;
}
double[] dailyReadings = { 22.5, 23.1, 21.8, 24.0, 22.9 };
// C# 14: the array converts implicitly — no .AsSpan() call needed
double avg = AverageTemperature(dailyReadings);
Console.WriteLine($"Average: {avg:F1}°C"); // Average: 22.9°C
// Span and ReadOnlySpan also compose more naturally with generics
ReadOnlySpan<char> greeting = "Hello, World!";
Span<char> buffer = new char[greeting.Length];
greeting.CopyTo(buffer);

Less ceremony around high-performance code means it’s easier to adopt these patterns throughout your codebase.


5. nameof with Unbound Generics — Cleaner Type Names

Previously, nameof required a closed generic type like nameof(Dictionary<string, int>) just to get back "Dictionary". In C# 14, you can pass the unbound form directly.

// Before C# 14 — you had to supply dummy type arguments:
string name1 = nameof(Dictionary<string, int>); // "Dictionary"
string name2 = nameof(List<object>); // "List"
// C# 14 — just use the unbound form:
string name3 = nameof(Dictionary<,>); // "Dictionary"
string name4 = nameof(List<>); // "List"
string name5 = nameof(Func<,,>); // "Func"
// Real-world use: building a generic cache key or log label
public static string CacheKey<T>() => $"cache:{nameof(List<>)}:{typeof(T).Name}";
Console.WriteLine(CacheKey<int>()); // cache:List:Int32
Console.WriteLine(CacheKey<string>()); // cache:List:String

6. Lambda Parameters with Modifiers — No Full Types Required

When a lambda parameter needed a modifier like ref or out, you previously had to write the full type for every parameter, even the ones you didn’t care about. Not anymore.

// A delegate for a try-parse style conversion
delegate bool TryConvert<TIn, TOut>(TIn input, out TOut result);
// Before C# 14 — all parameter types had to be spelled out:
TryConvert<string, int> parseOld = (string text, out int result) =>
int.TryParse(text, out result);
// C# 14 — just add the modifier, skip the type:
TryConvert<string, int> parseInt = (text, out result) => int.TryParse(text, out result);
TryConvert<string, bool> parseBool = (text, out result) => bool.TryParse(text, out result);
// Works great for inline swap utilities with ref params:
delegate void Swapper<T>(ref T a, ref T b);
Swapper<int> swap = (ref a, ref b) => (a, b) = (b, a);
int x = 10, y = 20;
swap(ref x, ref y);
Console.WriteLine($"x={x}, y={y}"); // x=20, y=10

7. Partial Constructors and Events — Better Source Generator Support

Source generators are a cornerstone of modern .NET tooling (think: EF Core, SignalR, logging). C# 14 extends the partial keyword to constructors and events, making generator-heavy classes much easier to split between generated and hand-written code.

// File: OrderProcessor.cs (your hand-written code)
public partial class OrderProcessor
{
// Defining declaration — no body, no initializer
public partial OrderProcessor(string region);
public void Process(Order order) => Console.WriteLine($"Processing in {_region}");
}
// File: OrderProcessor.Generated.cs (source generator output)
public partial class OrderProcessor
{
private readonly string _region;
private readonly ILogger _logger;
// Implementing declaration — has the body and base/this call
public partial OrderProcessor(string region) : base()
{
_region = region;
_logger = LoggerFactory.Create(b => b.AddConsole()).CreateLogger<OrderProcessor>();
_logger.LogInformation("OrderProcessor created for region: {Region}", region);
}
}

Your hand-written file stays clean and readable. The generated file handles all the plumbing. No mismatch, no duplication.


8. User-Defined Compound Assignment Operators

Custom types can now define their own behavior for compound operators like +=, -=, and *=. Previously this was inferred from the binary operator; now you can override it directly for full control.

public struct Budget
{
public decimal Amount { get; private set; }
public Budget(decimal amount) => Amount = amount;
// Standard addition
public static Budget operator +(Budget a, Budget b) => new(a.Amount + b.Amount);
// User-defined compound: += can now enforce a cap rule
public static Budget operator +=(Budget current, Budget extra)
{
var newAmount = current.Amount + extra.Amount;
return new Budget(Math.Min(newAmount, 100_000m)); // cap at 100k
}
public override string ToString() => $"${Amount:N0}";
}
var budget = new Budget(90_000m);
budget += new Budget(15_000m); // would be 105k — capped to 100k
Console.WriteLine(budget); // $100,000

Getting Started with C# 14 Today

All of these features are available now. To try them out:

C# 14 continues the language team’s philosophy of removing friction without adding complexity. Each of these features solves a real daily annoyance — and the cumulative effect on code readability is significant.

Source: What’s new in C# 14 — Microsoft Learn

VS Code Workspace & few example use cases for customizing your VS Code workspace:

what is a VSCode Workspace ?

A VS Code workspace is a feature in Visual Studio Code that allows you to organize your projects, files, and settings in a cohesive environment. Workspaces can be as simple as a single folder containing your project files, or as complex as a multi-root workspace that includes multiple folders and projects.

Here are some key aspects of a VS Code workspace:

  1. Single Folder Workspace: The most basic form, where you open a single folder containing your project files.
  2. Multi-root Workspace: Allows you to work on multiple projects simultaneously by adding multiple folders to the same workspace.
  3. Workspace Settings: Customize settings specific to your workspace, such as editor preferences, extensions, and debugging configurations.
  4. Launch Configurations: Manage launch configurations for debugging your projects.
  5. Task Configurations: Define tasks for building, testing, and running your projects.

To get started with a workspace, you can simply open a folder in VS Code. For more complex setups, you can create a multi-root workspace by selecting “Add Folder to Workspace” from the File menu.

1. Workspace Settings

Use Case: You’re working on a Python project and want to enforce specific linting rules.
Solution: Configure workspace settings to enable pylint and set custom rules.

{
    "python.linting.pylintEnabled": true,
    "python.linting.pylintArgs": ["--max-line-length=100"]
}

2. Adding Extensions

Use Case: You’re developing a web app and need tools to streamline your workflow.
Solution: Install extensions like Live Server, ESLint, and Prettier.

{
    "recommendations": [
        "ritwickdey.liveserver",
        "dbaeumer.vscode-eslint",
        "esbenp.prettier-vscode"
    ]
}

3. Multi-root Workspaces

Use Case: You have frontend and backend projects that need to be worked on simultaneously.
Solution: Add both projects to a single workspace for easier navigation and management.

"folders": [
    {
        "path": "frontend"
    },
    {
        "path": "backend"
    }
]

4. Task Configurations

Use Case: You need to automate the build process for a Node.js application.
Solution: Create tasks to install dependencies and run the build script.

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Install Dependencies",
            "type": "npm",
            "script": "install",
            "group": "build"
        },
        {
            "label": "Build Project",
            "type": "npm",
            "script": "build",
            "group": "build"
        }
    ]
}

5. Launch Configurations

Use Case: You’re debugging a Python application and need to set breakpoints and environment variables.
Solution: Configure launch settings to run your application with necessary parameters.

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "env": {
                "FLASK_ENV": "development"
            }
        }
    ]
}

6. Custom Keybindings

Use Case: You frequently need to format your code and want a custom shortcut.
Solution: Create a custom keybinding for the format document action.

{
    "key": "ctrl+shift+f",
    "command": "editor.action.formatDocument"
}

7. Snippets

Use Case: You often use a specific code pattern for React components.
Solution: Create a snippet to insert the boilerplate code quickly.

"React Component": {
    "prefix": "rfc",
    "body": [
        "import React from 'react';",
        "",
        "const ${1:ComponentName} = () => {",
        "    return (",
        "        <div>",
        "            ${2:/* component code */}",
        "        </div>",
        "    );",
        "};",
        "",
        "export default ${1:ComponentName};"
    ],
    "description": "Create a React functional component"
}

8. Theme and Appearance

Use Case: You prefer a dark theme and custom icons for a better coding experience.
Solution: Change the color theme and icon theme.

{
    "workbench.colorTheme": "Dark+ (default dark)",
    "workbench.iconTheme": "vscode-icons"
}

These examples demonstrate how customizing your workspace can streamline your development process, improve efficiency, and create a more enjoyable coding environment. 🌟

Do you have any specific customization in mind, or would you like more examples?

(This article was created with assistance from AI)

Create a Console app and run in a Container with Visual Studio 2022

I couldn’t find an article on this topic . so i thought i will put one .

Now there are many ways to interact with the container .You can do it with visual studio , Docker Desktop /terminal window
The following shows how to interact with the console app running in container using visual studio .
click the button shown below to open the terminal window .

It opens the power shell in the /app directory
cd in to the the directory that has the dll file .Fo e.g in this case it will be
cd /app/bin/Debug/net9.0/
dotnet <.dllfile>
Now you will be able to interact with it


Another way to do it is to build the image from the docker file generated by visual studio, as shown below

so try to open a separate terminal window to interact with the container .

here i built the image from the docker file visual studio generated and then started a container from it.using the following command
D:\LocalProjects\2024\DotNetConsoleApps\JuiceShop.Solution>docker buildx build -t juiceshop:v2 -f ./JuiceShop/Dockerfile .
The following is the output of theabove command

Once the above command is successful , it created a container image .

if you have installed docker desktop you could see this local image .

Now, to spin a container from the image , you can execute the following command in the terminal
docker run -it –name “zzzz” juiceshop:v2

if you don’t specify –name followed by container name (in this example zzzz) then docker gives an arbitrary name to the container.

Run the container
docker run -it –name “zzzz” juiceshop:v2
Hello please enter your name ?
Ethan Hunt
hello Ethan Hunt


Connect to localdb\mssqllocaldb in visual studio Server Explorer

The following are the steps to connect LocalDB in Visual Studio,

  • To connect to LocalDB in Visual Studio, follow these steps
  • Open Visual Studio and go to the Server Explorer window.
  • Right-click Data Connections and select Add Connection.
  • In the Add Connection dialogue box, select Microsoft SQL Server as the data source.
  • In the Server Name box, type (localdb)\MSSQLLocalDB.
  • Select Windows Authentication as the authentication method.
  • Click Test Connection to verify that the connection is successful.
  • Click OK to close the dialogue box and save the connection.

C#11-And , Or Operators in lambda Expressions

we can use the new and and or operators in C# 11 to create enhanced lambda expressions as follows

using System;

class Program
{
    static void Main(string[] args)
    {
        Func<int, bool> isEven = x => x % 2 == 0;
        Func<int, bool> isPositive = x => x > 0;

        // Using the 'and' operator
        Func<int, bool> isEvenAndPositive = isEven and isPositive;
        Console.WriteLine(isEvenAndPositive(4)); // Output: True
        Console.WriteLine(isEvenAndPositive(-4)); // Output: False

        // Using the 'or' operator
        Func<int, bool> isEvenOrPositive = isEven or isPositive;
        Console.WriteLine(isEvenOrPositive(4)); // Output: True
        Console.WriteLine(isEvenOrPositive(-4)); // Output: True
    }
}

DotnetCore Series

Installing dotnetcore on Fedora Linux

Screen 1 : Open a Terminal Window and type the command – dnf install dotnet-sdk-<version>
Screen 2
Screen 3 – Installation Complete