runtime: Why does DisablePrivateReflection attribute not work on .net core 2.1, but works perfectly on .net core 2.0?

Hello!

Why does DisablePrivateReflection attribute not work on .net core 2.1, but works perfectly on .net core 2.0?

I have a class with private fields. The class is in assembly marked with a DisablePrivateReflection attribute.

The following test will be passed successfully on .net core 2.0

var field = typeof(MonLicenseManager).GetField("_licenses", BindingFlags.NonPublic | 
BindingFlags.Static);

Assert.IsNotNull(field);

try
{
    var value = field.GetValue(null);
    Assert.Fail("FieldAccessException must be thrown");
}
catch (FieldAccessException)
{

}

but on .net core 2.1, FieldAccessException will never be thrown

Thanks

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 1
  • Comments: 22 (22 by maintainers)

Most upvoted comments

Long story short: please don’t bring it back. Imo, it should’ve never been existed in the first place.

This attribute is interesting for two reasons:

  • Size optimizations: e.g. IL Linker can safely strip names and attributes on things without having to worry that it might change semantics compared to the state before linking (modulo things like stack traces). We could even give non-generic types/members compilercontrolled visibility (i.e. members are referred to by tokens, not by names where we don’t even have to bother generating short unique names for them). Cc @marek-safar, @vitek-karas
  • Codegen optimization: none of the top-down codegen optimizations (the ones where in optimizing callee we assume we know values of parameters at all callsites) are safe to do in .NET because reflection allows calling anything with any values. When reflection is out of picture, these optimizations are safe. I know WASM has to do these illegal optimization to get size down (knowledge about parameters that are never passed as null). These optimizations would be safe when (at least the private) reflection can be disallowed and this is enforced by all runtimes. Cc @vargaz @AndyAyersMS @erozenfeld

If punted, we will have gone three major releases (2.1, 3.1, 5.0) without this functionality. I don’t really see many people clamoring to bring this back. If we’re unlikely ever to bring it back I’d rather close the issue (and obsolete the type) rather than continue punting.

This was not expected. We should keep respecting the DisablePrivateReflection attribute.