Thursday, April 17, 2025

C# 14.0: Introducing Extension Members and Null-Conditional Assignment

Visual Studio 17.14.0 Preview 3.0 got released earlier today and now you can try out two nice C# 14.0 features that got released with .NET 10 Preview 3.0.

Extension Members


We all know about Extension Methods which was there since C# 3.0.
public static class INumberExtensions
{
    public static IEnumerable<int> WhereGreaterThan(this IEnumerable<int> sourceint threshold)
    {
        return source.Where(x => x > threshold);
    }

    public static bool AnyGreaterThan(this IEnumerable<int> sourceint threshold)
    {
        return source.WhereGreaterThan(threshold).Any();
    }
}
So here I have some extension methods for IEnumerable<int> which I can call like below:
IEnumerable<int> numbers = [1, 2, 3, 4, 5];

IEnumerable<int> largeNumbers = numbers.WhereGreaterThan(3);
bool hasLargeNumbers = numbers.AnyGreaterThan(3);
With C# 14.0, I can write the same with following syntax. Note: there is no use of this.
public static class INumberExtensions
{
    extension(IEnumerable<int> source)
    {
        public IEnumerable<int> WhereGreaterThan(int threshold)
            => source.Where(x => x > threshold);

        public bool AnyGreaterThan(int threshold)
            => source.WhereGreaterThan(threshold).Any();
    }
}
It also supports generic types, something like following:
using System.Numerics;

public static class INumberExtensions
{
    extension<T>(IEnumerable<T> source)
        where T : INumber<T>
    {
        public IEnumerable<T> WhereGreaterThan(T threshold)
            => source.Where(x => x > threshold);

        public bool AnyGreaterThan(T threshold)
            => source.WhereGreaterThan(threshold).Any();
    }
}

Null-Conditional Assignment


Consider the below class.
public class Person
{
    public required string Name { getinit}

    public DateOnly? Birthdate { getset}

    public string? Address { getset}
}
And say we need to have a method to update person details.
static void UpdatePerson(Person? personDateOnly birthdatestring address)
{
    if (person is null)
    {
        return;
    }

    person.Birthdate = birthdate;
    person.Address = address;
}
Here we need to explicitly check whether the person is null before assignment. Now with C# 14.0, we can do this:
static void UpdatePerson(Person personDateOnly birthdatestring address)
{
    person?.Birthdate = birthdate;
    person?.Address = address;
}
And this is exactly same as previous code, values will only get set if the person is not null.

Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment