Reputation: 333
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?
Upvotes: 3
Views: 644
Reputation: 432
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')
Upvotes: 2
Reputation: 3475
StackTrace is string property of Exception, so if you loop through its member using foreach, its member should be character data type (char). You could simply convert to
If (ex.StackTrace.Length > 0)
{
messagestr += ex.StackTrace;
}
Upvotes: 1
Reputation: 29026
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
Upvotes: 1