System.MethodAccessException Class

The exception that is thrown when there is an invalid attempt to access a method, such as accessing a private method from partially trusted code.

See Also: MethodAccessException Members

Syntax

[System.Runtime.InteropServices.ComVisible(true)]
public class MethodAccessException : MemberAccessException

Remarks

Note:

This exception is not included in the tp://go.microsoft.com/fwlink/?LinkID=247912 or the Portable Class Library, but it is thrown by some members that are. To catch the exception in that case, write a catch statement for MemberAccessException instead.

This exception is thrown in situations such as the following:

Note:

Beginning with the net_v40_long, the common language runtime treats application code as transparent when it is run with partial trust. See Security Considerations for Reflection.

MethodAccessException uses the HRESULT COR_E_METHODACCESS, that has the value 0x80131510.

For a list of initial property values for an instance of MethodAccessException, see the MethodAccessException.#ctor constructors.

Thread Safety

All public static members of this type are safe for multithreaded operations. No instance members are guaranteed to be thread safe.

Example

The following example demonstrates a scenario under which MethodAccessException is thrown.

The following code contains a class with a public method (MyMethod). This class is compiled into a class library.

C# Example

using System;
namespace TestNameSpace 
{
 public class Class1
 {
   public Class1()
   {
     Console.WriteLine ("Constructing with public method.");
   }
   public void MyMethod () 
   {
     Console.WriteLine ("Calling MyMethod.");
   }
 }
}
      

The following code references the class library above, and accesses TestNameSpace.Class1.MyMethod. This code is compiled into an application.

C# Example

using System;
using TestNameSpace;
class AppTest
{
 public static void Main()
 {
   Class1 test = new Class1();
   test.MyMethod();
 }
}
      

The output of the application is

Constructing with public method.
Calling MyMethod.

The code for the class library is changed and recompiled so that TestNameSpace.Class1.MyMethod is no longer public. The following code changes MyMethod from public to private.

C# Example

using System;
namespace TestNameSpace 
{
 public class Class1
 {
   public Class1()
   {
     Console.WriteLine ("Constructing with private method.");
   }
   private void MyMethod () 
   {
     Console.WriteLine ("Calling MyMethod.");
   }
 }
}
      

When the application is executed again without being recompiled, the output is

Unhandled Exception: System.MethodAccessException: TestNameSpace.Class1.MyMethod()
at AppTest.Main()

Requirements

Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0, 4.0.0.0