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?
To stop executing java code just use this command: System. exit(1);
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.
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.
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!"
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With