Skip to content

Instantly share code, notes, and snippets.

View nickalbrecht's full-sized avatar

Nick Albrecht nickalbrecht

View GitHub Profile
@nickalbrecht
nickalbrecht / CombineFormattableStrings.cs
Created November 24, 2023 19:18
An extension method for use on a FormattableString to allow combining them, but keeping the output as a FormattableString, not string. I added this to allow passing it to EFCore, and let it handle parameterizing the command. Otherwise you have to do this yourself and call the RawSql variant of methods and pass in the parameters yourself. I'm not…
[GeneratedRegex(@"\{(\d+)\}")]
private static partial Regex FormattableStringArgumentRegex();
/// <summary>
/// Extension method for combining two <see cref="FormattableString"/>, and returning a new <see cref="FormattableString"/> with the combined arguments and format
/// </summary>
/// <remarks>Originally added to facilitate dynamically building up querystrings that EFCore would take and excute</remarks>
public static FormattableString Combine(this FormattableString baseFormattableString, FormattableString addingFormattableString)
{
var regex = FormattableStringArgumentRegex();
@nickalbrecht
nickalbrecht / IsNullOrDefault.cs
Created March 18, 2025 00:02
Generic extension method to check if any variable backed by a nullable value type is `null`, or whatever their default value is. I use it for dealing with `Guid?` but it would work with any value type such as `int?` to combine checks of it it's null or holds the default value for that type. `NotNullWhen` is for when the project has the Nullable …
public static partial class ExtensionMethods
{
public static bool IsNullOrDefault<T>([NotNullWhen(false)] this T? value) where T : struct
{
//return value == null || value.Equals(default(T)); Simpler, but my research online recommended using EqualityComparer<T>.Default instead of value.Equals
return !value.HasValue || EqualityComparer<T>.Default.Equals(value.Value, default);
}
}