Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return type of Exception StackTrace

Tags:

c#

vb.net

Hi I am writing C# codes from legacy VB Codes, I have a function:

Public Shared Sub logError(ByVal ex As Exception, ByVal additionalInfo As String) 
    Dim messagestr As String
    If ex.StackTrace.Length > 0 Then
        For Each stackTrace As String In ex.StackTrace
             messagestr &= stackTrace
        Next
    End If

I converted the for loop as:

foreach (string stackTrace in ex.StackTrace)
{
      messagestr += stackTrace;
}

There is an error message under 'foreach': "Cannot convert type 'char' to 'string'.

It's quite weird as I read the StackTrace from MSDN that it returns a string. So I don't know why there is a for loop in the legacy VB codes. Also, I don't where the 'char' comes from.

I think I am complete lost in this area. Can anybody help me out?

like image 256
DennisL Avatar asked Sep 10 '26 06:09

DennisL


2 Answers

The return type of ex.StackTrace is a string. The object that you will get by iterating over a string is char not another string. So you foreach loop must be:

foreach (char stackTrace in ex.StackTrace)
{

}

Or simply append stack trace to your string:

messagestr += ex.StackTrace;

If you want to get all function calls separately use this code to split your string into lines:

var stackLines = ex.StackTrace.Split('\n')
like image 190
Feriloo Avatar answered Sep 12 '26 19:09

Feriloo


According to the documentation StackTrace Gets a string representation of the immediate frames on the call stack.

So when you iterate a string which will actually iterate through its characters, this is happening in your case.

Where as in VB it Represents a stack trace, which is an ordered collection of one or more stack frames. so when you iterate it iterates through the frames

like image 40
sujith karivelil Avatar answered Sep 12 '26 20:09

sujith karivelil