Accessing private members using reflections in C#/Silverlight code RRS feed

  • Question

  • My code invokes method using reflection:

    BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic,
    null, scoringInstance,
    new object[] { sArg, eArg });
    where scoringInstance is an instance of a ModelView class. The method is private, but I use BindingFlags.NonPublic, so, i should be able to access it, but I cannot - I get MethodAccessException exception: "Attempt by method ... to access method ... failed."
    Google doesnt seem to have an answer. Do you have any idea how to fix it by any chance?
    Thursday, September 1, 2011 10:13 PM


  • InvokeMember for private members only works in a Fully Trusted environment.  From the docs:


    "Access restrictions are ignored for fully trusted code; that is, private constructors, methods, fields, and properties can be accessed and invoked through System.Reflectionwhenever the code is fully trusted."

    If you're running this in a partial trust scenario (like Silverlight in browser), you'll get this exception, as you are not allowed to access private members.

    Reed Copsey, Jr. -
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    Thursday, September 1, 2011 10:34 PM