What is a method that's inside another method called?

Viewed 3244

What type of method is String dgvValue(int cell) in the below code?

private void btnEdit_Click(object sender, EventArgs e)
{
    if (dgvGuestList.SelectedRows.Count > 0)
    {
        String dgvValue(int cell)
        {
            return dgvGuestList.SelectedRows[0].Cells[cell].Value.ToString();
        }
        
        editGuest editGuest = new editGuest(int.Parse(dgvValue(0)), dgvValue(1), 
        int.Parse(dgvValue(2)), dgvValue(0), dgvValue(0), dgvValue(0), dgvValue(0));
        editGuest.ShowDialog();
    }
    else
    {
        DialogResult error = MessageBox.Show("No row selected.", "Error", MessageBoxButtons.OK, 
        MessageBoxIcon.Exclamation);
    }
}
2 Answers

It's a feature of c# called local functions, introduced in c# 7:

Many designs for classes include methods that are called from only one location. These additional private methods keep each method small and focused.
Local functions enable you to declare methods inside the context of another method. Local functions make it easier for readers of the class to see that the local method is only called from the context in which it is declared.

The technical term is "closure", and it is very common in functional languages. The wikipedia page gives a number of examples and good overview of what they do:

Operationally, a closure is a record storing a function together with an environment. The environment is a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created. Unlike a plain function, a closure allows the function to access those captured variables through the closure's copies of their values or references, even when the function is invoked outside their scope.

See also these tutorials on javascript closures and python closures.


Also, although I cannot comment due to reputation, I want to push back on @infinitezero's comment on the accepted answer:

It's also called a "wth does this function do?"-function. Remember that code is meant to be read by humans, not computers, so comprehensive naming should be paramount.

While it is true that code is read by humans, sometimes this design decision is appropriate (see examples in tutorials) and can dramatically simplify code. In the original example, note that the

.SelectedRows[0].Cells[cell].Value.ToString

is rather long, and copying this seven times would be much harder to read and edit than to simply change the function. Moreover, this function could well no meaning outside of the btnEdit_Click function, and so making it local is appropriate, even though generating the closure is more computationally expensive. I would therefore argue that the reason to use closures is because code is written for humans and not computers.

Related