Call Stack
- When you invoke a method, the CLR allocates some memory to keep track of that method’s state.
- This state includes incoming arguments and local variables.
- When a method calls out to another method, the method state also remembers where we were in the calling method’s code to be able to carry on later.
- If you have nested method calls you end up with a sequence of method states, and this sequence is often referred to as the call stack.
- In general, a stack is a sequence of items where you can add or remove items only at the end of the sequence.
- When C# code invokes a new method, it pushes a new method state record onto the call stack.
- When the method returns, either because execution reaches the end or because we’ve hit a return statement, the current method state is popped from the call stack, and then execution resumes from where the previous method state record says the calling method had reached.
- As calls complete, the call stack shrinks until another series of methods are invoked.
- The term for describing the process of removing calls from the call stack is stack unwinding.
- Stack unwinding always occurs in the reverse order of the method calls.
- The result of method completion is that execution will return to the call site, which is the location from which the method was invoked.
Method Resolution
- At a high level, selection by the compiler governing which method to call is determined to be whichever applicable method is most specific.
- There can be only one method that matches the caller parameters identically, so this will always take precedence.
- Assuming there are two applicable methods, each requiring an implicit conversion, the method that matches the most derived type will be used.
- A method using double will be favored over a method using object if the caller passes an int.
- This is because double is more specific than object.
Parameter Arrays (params)
static void Print(params string[] paths)
{
foreach (string path in paths)
Console.WriteLine(path);
}
Characteristics
- The parameter array must be the last parameter in the method declaration.
- A method cannot have more than one parameter array.
- The caller can specify zero parameters for the parameter array.
- They are type-safe: the type must match the type identified by the array.
- The caller can use an explicit array rather than a comma-separated list of parameters. The resultant CIL code is identical.