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
string.Emptyinstead of"", you never need to worry about assigning an empty string - it's free. The compiler always assigns the same instance, so that you don't waste any memory at all.""also reuses the same instance.p.LabelUrlis null, your current code will replace it with"", but you say that you "need to set a value only if a property is not null" - which contradicts what your example code is actually doing.