C# - Get All Stack Frames Using StackTrace Class

Here, we are going to learn how to get all stack frames using StackTrace class in C#? By Nidhi Last updated : March 28, 2023

Here, we will get stack frames(method name, module name) using StackTrace and StackFrame classes.

C# program to get all stack frames using StackTrace class

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# - 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 »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.