When using a string builder, I get expected results from the append and append line functions when using an enum is the input, but when the enum is boxed the append line and append function give differing results.
Can anyone tell me what may be behind this?
Code output:
Append Enum: 1
Append Enum To String: One
Append Line Enum: 1
Append Line Enum To String: One
Append Object: One
Append Object To String: One
Append Line Object: 1
Append Line Object To String: One
Code:
Public Enum eTest
One = 1
Two = 2
End Enum
Sub Main()
Dim sb As New System.Text.StringBuilder()
Dim x = eTest.One
sb.Append("Append Enum: ").Append(x).AppendLine()
sb.Append("Append Enum To String: ").Append(x.ToString()).AppendLine()
sb.Append("Append Line Enum: ").AppendLine(x)
sb.Append("Append Line Enum To String: ").AppendLine(x.ToString())
Dim o As Object = x
sb.Append("Append Object: ").Append(o).AppendLine()
sb.Append("Append Object To String: ").Append(o.ToString()).AppendLine()
sb.Append("Append Line Object: ").AppendLine(o)
sb.Append("Append Line Object To String: ").AppendLine(o.ToString())
Console.WriteLine(sb.ToString())
'===============================
Console.ReadKey()
End Sub
This line
causes
o.ToString()to be appended to the instance ofStringBuilderand that is the difference. Of course, that call just passes through to the boxed instance of your enum and this is why you seeOnefor this invocation.This is because you are invoking the overload
StringBuilder.Append(object)which will just invokeo.ToString()on the passed in instance of object. This is explicitly in the documentation:On the other hand, when you call
where
xis an instance of an enum,xwill be implicitly converted to an instance ofintwhich will call the overloadStringBuilder.Append(int).Note that this is specific to VB.NET. C# will not implicitly convert
xto anintwhen choosing which overload ofStringBuilder.Appendto invoke; it will invokeStringBuilder.Append(object).