Last active
November 23, 2020 04:45
-
-
Save jiripolasek/9d18bb51af08f58f04c26c773b835ab1 to your computer and use it in GitHub Desktop.
Detect init-only property using reflection
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 ReflectionExtensions | |
{ | |
/// <summary> | |
/// Gets a value indicating whether property has init accessor declared. | |
/// </summary> | |
/// <param name="propertyInfo"></param> | |
/// <returns>Returns <c>true</c> if the property is declared as init-only; otherwise returns <c>false</c>.</returns> | |
public static bool IsInitOnly(this PropertyInfo propertyInfo) | |
{ | |
if (propertyInfo == null) | |
throw new ArgumentNullException(nameof(propertyInfo)); | |
// return type of init-only property setter has custom modifier applied to it: modreq(System.Runtime.CompilerServices.IsExternalInit) | |
// e.g.: .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) Net5FeaturesDemo.TestClass::set_TestProperty(int32) | |
return propertyInfo | |
.SetMethod? | |
.ReturnParameter | |
.GetRequiredCustomModifiers() | |
.Any(modifierType => modifierType.FullName == "System.Runtime.CompilerServices.IsExternalInit") == true; | |
// .Contains(typeof(System.Runtime.CompilerServices.IsExternalInit)) == true; // type is only available in .NET 5 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment