'GetRuntimeProperty violates encapsulation principles

Please explain why using GetRuntimeProperty you can change the private field of the class? It also violates all the principles of encapsulation. Is this a bug in the .Net platform or was it intended that way? And there is nothing wrong with that.

using System.Reflection;
 
namespace TestDLL
{
    class Program
    {
        static void Main(string[] args)
        {
            var t = new Test();
            //t.Id25 = 10; Ошибка!
            //t.id = 10;   Ошибка!
            var r = t.Id25; // == 25
            t.GetType().GetRuntimeProperty("Id25").SetValue(t, 100);
            r = t.Id25; // == 100
        }
 
    }
    class Test
    {
        public int Id25 { get => id; private set => id = value; }
        private int id;
        public Test()
        {
            id = 25;
        }
    }
}


Solution 1:[1]

From the PropertyInfo.SetValue method documentation:

Note
Starting with the .NET Framework 2.0 Service Pack 1, this method can be used to access non-public members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public members is restricted to the caller's grant set, or a subset thereof. (See Security Considerations for Reflection.) To use this functionality, your application should target the .NET Framework 3.5 or later.

References

https://docs.microsoft.com/en-us/dotnet/api/system.reflection.propertyinfo.setvalue?view=net-6.0#system-reflection-propertyinfo-setvalue(system-object-system-object)

https://docs.microsoft.com/en-us/dotnet/api/system.security.permissions.reflectionpermissionflag?view=dotnet-plat-ext-6.0&viewFallbackFrom=net-6.0#system-security-permissions-reflectionpermissionflag-restrictedmemberaccess

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 evilmandarine