I would solve this using the extension method as follows:
public static void AddIfNotNull<T>(this List<T> list, T? value) where T : struct { if(value != null) { list.Add(value.Value); } }
How can it be used as follows:
var ids = new List<Guid>(); ids.AddIfNotNull(projectId);
Perhaps not as "cunning" (and not one-line) as your proposal, but, in my opinion, it is much easier to read and understand. If you want to use it as a single line, you could change the type of extension return as a list. This would allow something like var ids = new List<Guid>().AddIfNotNull(projectId);
source share