Principal
When are the arguments of a deferred function calculated? At the time of definition or at the time of call?
sobes.tech AI
Answer from AI
C# does not have the keyword defer — this is a construct from the Go language. If the question is about Go, then the arguments of the deferred function defer are evaluated at the moment of definition (that is, when the line with defer is executed), and the function itself is called later, upon exiting the current function.
Example in Go:
func example() {
x := 5
defer fmt.Println(x) // x is evaluated now, value 5 is saved
x = 10
}
// When exiting example(), 5 will be printed, not 10
If the question is about C#, then an equivalent to defer could be using or constructs with try/finally, where arguments are evaluated at the moment of call, and resource release happens later.