Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to forbid calling a method C#

I want to allow calling the method only from the particular methods. Take a look at the code below.

  private static void TargetMethod()
  {
  }

  private static void ForbiddenMethod()
  {
     TargetMethod();
  }

  private static void AllowedMethod()
  {
     TargetMethod();
  }

I need only AllowedMethod could call TargetMethod. How to do it using classes from System.Security.Permissions?

Updated: Thanks for your answers, but I don't want to debate about design of my application. I just want to know is it possible to do it using .net security or not?

like image 898
Alexander G Avatar asked Jan 15 '10 12:01

Alexander G


People also ask

How do I stop a method from running?

To stop executing java code just use this command: System. exit(1);

How do I stop a method in C#?

Use the break Statement to Exit a Function in C# The break statement stops the loop where it is present. Then, if available, the control will pass to the statement that follows the terminated statement.

How to define Methods in C#?

Methods are declared in a class, struct, or interface by specifying the access level such as public or private , optional modifiers such as abstract or sealed , the return value, the name of the method, and any method parameters. These parts together are the signature of the method.

How to call a method inside main method in C#?

Call a Method Inside Main() , call the myMethod() method: static void MyMethod() { Console. WriteLine("I just got executed!"); } static void Main(string[] args) { MyMethod(); } // Outputs "I just got executed!"


2 Answers

You can solve this using normal object-oriented design. Move AllowedMethod to a new class and make ForbiddenMethod a private method of that class:

public class MyClass
{
    public void AllowedMethod() { // ... }

    private void TargetMethod() { // ... }
}

AllowedMethod has access to private members, but no-one else have.

like image 116
Mark Seemann Avatar answered Sep 20 '22 08:09

Mark Seemann


I believe you should try to structure your code in meaningfull classes, and use the standard access modifiers (private, protected, public, internal). Is there any specific reason why this would not solve your problem?

The only alternative I can think of, would involve traversing the call stack from within the callee, but that would likely yield code mess and suboptimal performance.

like image 31
Jørn Schou-Rode Avatar answered Sep 21 '22 08:09

Jørn Schou-Rode