Skip to content

Instantly share code, notes, and snippets.

@jnm2
Last active February 24, 2025 02:37
Show Gist options
  • Save jnm2/96cd9d1d142cd66cbddfd63da73cb488 to your computer and use it in GitHub Desktop.
Save jnm2/96cd9d1d142cd66cbddfd63da73cb488 to your computer and use it in GitHub Desktop.
using System.Reflection;
internal static class ReflectionUtils
{
public static bool IsVisibleOutsideAssembly(Type type)
{
return (type.Attributes & TypeAttributes.VisibilityMask) switch
{
TypeAttributes.Public => true,
TypeAttributes.NestedFamily or TypeAttributes.NestedFamORAssem => IsVisibleOutsideAssembly(type.DeclaringType!),
_ => false,
};
}
public static bool IsVisibleOutsideAssembly(MethodInfo method, bool assumeDeclaringTypeIsVisibleOutsideAssembly = false)
{
return (method.Attributes & MethodAttributes.MemberAccessMask) switch
{
MethodAttributes.Public or MethodAttributes.Family or MethodAttributes.FamORAssem =>
assumeDeclaringTypeIsVisibleOutsideAssembly || IsVisibleOutsideAssembly(method.DeclaringType!),
_ => false,
};
}
public static bool IsInitOnly(MethodInfo method)
{
return method.ReturnParameter.GetRequiredCustomModifiers().Any(m => m.FullName == typeof(IsExternalInit).FullName!);
}
public static bool IsReadOnly(MethodInfo method)
{
return HasAttribute(method, typeof(IsReadOnlyAttribute).FullName!);
}
public static bool IsReadOnly(Type type)
{
return HasAttribute(type, typeof(IsReadOnlyAttribute).FullName!);
}
private static bool HasAttribute(MemberInfo member, string attributeFullName)
{
return member.GetCustomAttributesData().Any(d => d.AttributeType.FullName == attributeFullName);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment