Is it possible to force one method to be called by another in a specific one?

3

I have a parent method that calls a child method, I wish the child method could only be called exclusively by the parent method, would it be possible?

Example:

public void MetodoPai(){
    //codigo
    MetodoFilho();
    //codigo
} 

void MetodoFilho(){
    //codigo
} 


public void OutroMetodoQualquer(){
    //codigo
    MetodoFilho(); //Causar erro na compilação ou algo do tipo
} 
    
asked by anonymous 25.04.2018 / 16:28

2 answers

3

If everything is within the same class (only with the comments this is clear) local function is the solution . Obviously you are limited to a method, you can not make a method accessible by a list of methods.

Everything must be within scope or specified scope in general, not specific, unless you make an external tool that is required to go through every build. One of the reasons for creating the .NET Compiler Platform is precisely to make this type of tool. But of course if not go through it will not prohibit anything.

Remembering that forcing or forbidding always occurs when the programmer wants to follow the standard protocols, if he wants to go over it, he always can. This would be a protection against an inadvertent error, not security against fraud.

If the local function does not match, the maximum the standard compiler allows is to prohibit its calling outside the class ( private ), outside the class hierarchy ( protected ) or outside the assembly ( internal ) or a combination of the last two, or you can limit it further and allow a method of the class to be the only one to access a function function . But you can not say nominally who can access.

You can say that can be accessed by some other assembly with an attribute .

    
25.04.2018 / 16:38
-1

Perhaps the best solution is to separate by classes, where the Parent method and the Child method are in the same class, but the child is private and can only be accessed from within the class itself. And a second class that implements the first. The second class will only view the Parent method because it is public. The Son method will be hidden for this second class.

What "Leonardo Bonetti" meant by problems is that Programs are built to solve a problem. That is, you need to add two numbers, that's the problem: "add two numbers". So you create solutions to solve this problem. Knowing what you need to solve, makes it easy for us to indicate a solution.

Anyway, class is the best way to solve this issue of hiding methods, but the right resolution is only possible knowing the scope of your problem.

    
25.04.2018 / 18:34