Skip to content

Instantly share code, notes, and snippets.

@jkotas
Last active November 5, 2022 01:18
Show Gist options
  • Save jkotas/ddfeb9ec47bff90b4249534c4cd0761a to your computer and use it in GitHub Desktop.
Save jkotas/ddfeb9ec47bff90b4249534c4cd0761a to your computer and use it in GitHub Desktop.
IgnoreAccessibilitySample
<?xml version="1.0" encoding="utf-8"?>
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
<InlineIL />
</Weavers>
namespace System.Runtime.CompilerServices
{
public class IgnoresAccessChecksToAttribute : Attribute
{
public IgnoresAccessChecksToAttribute(string assemblyName)
{
AssemblyName = assemblyName;
}
public string AssemblyName { get; }
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Fody" Version="6.6.4" PrivateAssets="all" />
<PackageReference Include="InlineIL.Fody" Version="1.7.2" PrivateAssets="all" />
</ItemGroup>
</Project>
using InlineIL;
using static InlineIL.IL.Emit;
// Ignore runtime access checks to itself
[assembly: System.Runtime.CompilerServices.IgnoresAccessChecksTo("IgnoreAccessibilitySample")]
Console.WriteLine(GetPrivateFieldFromUserDefinedType(new UserDefinedType(false)));
Console.WriteLine(GetPrivateFieldFromUserDefinedType(new UserDefinedType(true)));
static bool GetPrivateFieldFromUserDefinedType(UserDefinedType u)
{
Ldarg_0();
Ldfld(new FieldRef(typeof(UserDefinedType), "_privateField"));
return IL.Return<bool>();
}
// ----------------
class UserDefinedType
{
bool _privateField;
public UserDefinedType(bool v)
{
_privateField = v;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment