|
-
Aug 6th, 2015, 08:26 AM
#1
Thread Starter
Hyperactive Member
[RESOLVED] Overload ToString for Byte array
Hi folks
First let me say that Im still a newb at VB 
I would like to overload the ToString() method for a byte array, or better yet, overload the Tostring() method for a UInt16 but only within a certain class (i.e. when I call UInt16.ToString withn Foo class it uses my overload, when I call it outside of Foo class it uses the standard method)
First, is the latter possible?
Secondly My reason for wanting to overload this is so that I can have it make a string of the hex values of each byte with some pretty formatting, e.g. if my array of two bytes is {&HA5, &H5A} Then MyArray.ToString will return a string = "5A A5" (Little-endian). Is overloads the way to go? Or an Override, or an Extension?
Thirdly I have tried Overloading as follows but the call in the same class still seems to use the normal ToString meaning it results in the name of the type ("System.Byte[]"), rather than anything useful.
VB Code:
Public Class Foo
Public Sub Bar ()
Dim MyInt As Integer = 42330
Dim MyString As New String(BitConverter.GetBytes(MyInt).ToString) ' Should use my Overload below
Dim BetterString As New String(MyInt.ToString) ' Should be "5A A5" not "42330"
End Sub
Public Overloads Function ToString(Of T)(a As Byte()) As String
Dim RetVal As New System.Text.StringBuilder(a.Length * 3)
Dim ByteStr As String
Dim Last As Integer = a.Length - 1
For i As Integer = 0 To Last
ByteStr = New String(Conversion.Hex(a(i)))
If ByteStr.Length = 1 Then
RetVal.Append("0")
End If
RetVal.Append(ByteStr)
If i <> Last Then
RetVal.Append(" ")
End If
Next
Return RetVal.ToString
End Function
End Class
Public Class Wiz
Public Sub Foo
Dim MyInt As Integer = 42330
Dim MyString As NewString(MyInt.ToString) ' Should always be "42330"
End Sub
End Class
Thanks!
Thanks 
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|