Created
February 21, 2023 21:45
-
-
Save stand-sure/dbf36c5f5a5e24ef6766e9751f254ea0 to your computer and use it in GitHub Desktop.
Verify that a property is Init Only
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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