Skip to content

Instantly share code, notes, and snippets.

@stand-sure
Created February 21, 2023 21:45
Show Gist options
  • Save stand-sure/dbf36c5f5a5e24ef6766e9751f254ea0 to your computer and use it in GitHub Desktop.
Save stand-sure/dbf36c5f5a5e24ef6766e9751f254ea0 to your computer and use it in GitHub Desktop.
Verify that a property is Init Only
public static class PropertyChecker
{
// usage: PropertyChecker.CheckInitOnly(() => foo.Bar);
public static void CheckInitOnly(Expression<Func<object>> expression, bool allowEmptyStrings = false)
{
if (expression.Body is not UnaryExpression { Operand: MemberExpression memberExpression })
{
if (expression.Body is not MemberExpression tmp)
{
throw new InvalidOperationException($"Expected a {nameof(MemberExpression)}.");
}
memberExpression = tmp;
}
var property = (PropertyInfo)memberExpression.Member;
var setMethod = property.GetSetMethod();
setMethod.Should().NotBeNull();
var isExternalInitType = typeof(System.Runtime.CompilerServices.IsExternalInit);
setMethod!.ReturnParameter.GetRequiredCustomModifiers().Should().Contain(isExternalInitType);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment