In C# this was not possible (has in C# 7, see more in another question here). Enough to create delegates, but I doubt it’s what you want.
As a matter of fact, I see little use for it. Normally this will only be necessary if the code is too large and yet, the solution is not to create Inner functions, as shown in Javascript. This is done in JS because it is a language that has limitations to limit visibility and scope.
The idea of structuring parts of the code into separate functions is good, it separates responsibilities, but it doesn’t have to be within. Create other functions outside of it. The only drawback of this is that externally any other method in the class can call it. If it were internal, only it could call the function. But this is not usually a problem.
Of course you should create this function/method, such as private
so it can’t be accessed outside the class.
public void Salva() => if (valida()) insereNoBanco();
private bool valida() {
// valida campos
}
private void insereNoBanco() {
// insere dados no banco
}
I wouldn’t do this but Daniel’s response put an example of what I initially said in the answer about lambda and which is the closest to the simulation of Inner fucntion used in Javascript:
public void Salva() {
Func<bool> valida = () => {
// valida campos
};
Action insereNoBanco = () => {
// insere dados no banco
};
if (valida()) insereNoBanco();
}
I put in the Github for future reference.
It is unnecessary to do this, can have unwanted effects and is not idiomatic in C#.
Good question, but it had some different interpretations, I suggest you read the answers carefully.
– David Schrammel
This Bruno, read carefully the answers and accept to which really responds well what you asked. If you still don’t know what acceptance is like, check out the [tour].
– Maniero