Home »
.Net »
C# Programs
C# program to get all stack frames using StackTrace class
Here, we are going to learn how to get all stack frames using StackTrace class in C#?
Submitted by Nidhi, on November 05, 2020
Here, we will get stack frames(method name, module name) using StackTrace and StackFrame class.
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.
//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.
C# Data Structure Programs »