Sebastian
Sebastian

Reputation: 4811

Using c# NULL coalescing operator with NOT NULL Scenarios

I am populating a Class using LINQ and LinkUrl is a string property of my class.I need to set a value only if a property is not null , other wise no need to assign any values Currently The conditional operator ?: is used

    var formattedData = dataset.Select(p => new  ListModel
    {
        Prop1=....,
        Prop2=....,
        ...
        LinkUrl = string.IsNullOrWhiteSpace(p.LabelUrl) ? "" : "SET MY PROPERRTY TO A VALUE",
        .....
    }).ToList();

Can we replace this with C#‘s null-coalescing operator (??) or (?.) or something similar ??

Tne intention is to avoid the repeated use of assigning to "" in so many places

I can write it with operator ?? , but handle cases of NULL only like below .

    LinkUrl = p.LabelUrl ?? "SET MY PROPERRTY TO A VALUE" 
    

Can we do something similar for Not null cases

Upvotes: 0

Views: 733

Answers (2)

Paulo Morgado
Paulo Morgado

Reputation: 14836

You can use one of the Null-coalescing assignment.

But it won't check for empty strings.

Upvotes: 0

Ivan Furdek
Ivan Furdek

Reputation: 914

I think closest you could get to a shorthand for not null would be a set of extension methods

    public static T NullOrValue<T>(this T nullable, T value) where T : class => nullable == null ? null : value;
    
    public static T? NullOrValue<T>(this T? nullable, T value) where T : struct => nullable == null ? (T?)null : value;

Which would then be available on any nullable object as

var value = anyObjectOrNullable.NullOrValue(MyValue);

Upvotes: 1

Related Questions