The source code to get all stack frames using StackTrace class is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# program to get all stack frames using StackTrace class
using System;
using System.Diagnostics;
class Demo
{
public static void Main()
{
StackTrace trace = new StackTrace();
StackFrame[] frames;
frames= trace.GetFrames();
Console.WriteLine("Frames: ");
foreach (StackFrame frame in frames)
{
Console.WriteLine("\tMethod Name: "+frame.GetMethod().Name);
Console.WriteLine("\tModule Name: "+frame.GetMethod().Module+"\n");
}
}
}
Output:
Frames:
Method Name: Main
Module Name: Test.exe
Press any key to continue . . .
Explanation:
In the above program, we created a Demo class that contains the Main() method, The Main() method is the entry point for the program, here, we created the object of StackTrace class and the get the stack frames using GetFrames() method. The GetFrames() returns the array of StackFrame. Then we access the frame one by one using the "foreach" loop. Here we printed the method names and module names on the console screen.
Program:
The source code to get all stack frames using StackTrace class is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
Output:
Explanation:
In the above program, we created a Demo class that contains the Main() method, The Main() method is the entry point for the program, here, we created the object of StackTrace class and the get the stack frames using GetFrames() method. The GetFrames() returns the array of StackFrame. Then we access the frame one by one using the "foreach" loop. Here we printed the method names and module names on the console screen.