user2878971
user2878971

Reputation:

FieldAccessException when accessing protected field via reflection

Why am I getting a FieldAccessException when trying to access a protected field with reflection in the following code?

using System;
using System.Reflection;

public class Program
{
    public static void Main()
    {
        Foo foo = new Foo();

        BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.NonPublic 
                                | BindingFlags.Public | BindingFlags.Static;
        FieldInfo fieldInfo = foo.GetType().GetField("field", bindFlags);

        Object fieldValue = fieldInfo.GetValue(foo);
    }
}

public class Foo 
{   
    public Foo() {
        field = 1;  
    }

    protected int field;    
}

This fiddle gives me the exception: https://dotnetfiddle.net/wu5vDX, but shouldn't the binding flags make sure that I am able to access the field?

Edit: Apparently, this is a .Net Fiddle only result. It only happens in the fiddle and not in Visual Studio for example.

Upvotes: 1

Views: 632

Answers (1)

haim770
haim770

Reputation: 49133

It's a restriction imposed by DotNetFiddle by not running your code in Full Trust (for security reasons). Hence you're unable to leverage all the capabilities of Reflection API.

From MSDN:

..., only trusted code can use reflection to access nonpublic members that would not be directly accessible to compiled code.

Upvotes: 2

Related Questions