Results 1 to 7 of 7

Thread: [RESOLVED] Overload ToString for Byte array

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2007
    Location
    cobwebbed to PC
    Posts
    311

    Resolved [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:
    1. Public Class Foo
    2.     Public Sub Bar ()
    3.         Dim MyInt As Integer = 42330
    4.         Dim MyString As New String(BitConverter.GetBytes(MyInt).ToString) ' Should use my Overload below
    5.         Dim BetterString As New String(MyInt.ToString) ' Should be "5A A5" not "42330"
    6.     End Sub
    7.  
    8.     Public Overloads Function ToString(Of T)(a As Byte()) As String
    9.         Dim RetVal As New System.Text.StringBuilder(a.Length * 3)
    10.         Dim ByteStr As String
    11.         Dim Last As Integer = a.Length - 1
    12.  
    13.         For i As Integer = 0 To Last
    14.             ByteStr = New String(Conversion.Hex(a(i)))
    15.             If ByteStr.Length = 1 Then
    16.                 RetVal.Append("0")
    17.             End If
    18.             RetVal.Append(ByteStr)
    19.             If i <> Last Then
    20.                 RetVal.Append(" ")
    21.             End If
    22.         Next
    23.         Return RetVal.ToString
    24.     End Function
    25. End Class
    26.  
    27. Public Class Wiz
    28.     Public Sub Foo
    29.         Dim MyInt As Integer = 42330
    30.         Dim MyString As NewString(MyInt.ToString) ' Should always be "42330"
    31.     End Sub
    32. End Class

    Thanks!
    Thanks

  2. #2
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Posts
    12,398

    Re: Overload ToString for Byte array

    Try doing something like this:
    Code:
    Public Class Foo
    
        Public Property Hexes As Byte()
    
        Public Overrides Function ToString() As String
            Dim RetVal As New System.Text.StringBuilder(Me.Hexes.Length * 3)
            Dim ByteStr As String
            Dim Last As Integer = Me.Hexes.Length - 1
            For i As Integer = 0 To Last
                ByteStr = New String(Microsoft.VisualBasic.Conversion.Hex(Me.Hexes(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
    
        Public Sub New(ByVal hexValues() As Byte)
            Me.Hexes = hexValues
        End Sub
    
    End Class
    I think that you could make your code inside the ToString more... .NET, but I just don't know enough about it to help. However the code I provided does what you want(I think).
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | HtmlLessons | CssLessons | Code Tags | Sword of Fury - Jameram

  3. #3
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,109

    Re: Overload ToString for Byte array

    I'd say that you are making this harder than you need to. Consider that if you didn't overload the .ToString method then you would be able to call Foo.ToString and you would get something back...something useless to you, but something. The point is that every object has an implementation of .ToString. An array of byte would have an implementation of .ToString as well, you just appear to want the situation that an array of byte in a certain context would have a different implementation of .ToString, and you appear to be tying yourself into knots to get there. It seems like there are better solutions, though which one would be best is hard to say.

    One option would be to create a class that wrapped the array of bytes. This class could overload .ToString however it wanted to, and the context wouldn't make any difference anymore. Wherever you used that class you'd have that overload available. You could give it a constructor that took an array of bytes as an argument, too, so converting a standard array of bytes into an instance of that class would be easy.

    Another option might be to create an extension method with a name other than .ToString. It would apply all the time, but so what? What's so special about the name .ToString.

    The third option, and likely the easiest, would be to create a function in a module that took an array of bytes as an argument and returned the formatting you wanted. After all, is it really that much different calling:

    ToString(myArrayOfBytes)

    versus

    myArrayOfBytes.ToString

    I'm not sure that you can create a method called ToString in a module, because that might cause a conflict, since a module is just a class under the hood, so it should have a .ToString implementation already, but the name could be changed easily enough.
    My usual boring signature: Nothing

  4. #4

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2007
    Location
    cobwebbed to PC
    Posts
    311

    Re: Overload ToString for Byte array

    @dday9:

    That would override the Object.ToString() for Foo, allowing a customisation of Foo.ToString(), wouldn't it?

    This is different to what I am trying to achieve which is to "subvert" the Integer.ToString() while within Foo

    A usage example:

    VB Code:
    1. Public Class Foo
    2.     Private _someInt As integer
    3.     Public sub New(ByVal i As Integer)
    4.         _someInt = i
    5.     End Sub
    6.  
    7.     Public Function GetByteString() As String
    8.         Return _someInt.ToString()
    9.     End Function
    10.  
    11.     Private Overloads Function ToString(i As Integer) As String
    12.          ' Does not overload Object.ToString for purpose of Foo.ToString,
    13.          ' but instead overloads Integer.ToString() for Foo.Integer.ToString() use
    14.  
    15.          ' ... Byte string conversion and formatting here ...
    16.          Return TheNewString
    17.     End Function
    18. End Class
    19.  
    20. Public Class MainClass
    21.     Public Sub Main()
    22.        Dim X As Integer = 42330
    23.        Dim Y as New Foo(42330)
    24.  
    25.        Console.WriteLine(X.ToString)    ' Prints "42330"
    26.        Console.WriteLine(Y.GetByteString)    ' Prints "5A A5"
    27.     End Sub
    28. End Class
    Last edited by wolf99; Aug 6th, 2015 at 10:28 AM.
    Thanks

  5. #5
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Posts
    12,398

    Re: Overload ToString for Byte array

    If that is the case then you should follow Shaggy's third option in post #3. Just create a module to hold various functions that convert some type(or array of type) to your desired string format:
    Code:
    Public Module LittleEndian
    	
    	Public Function GetByteString(ByVal values() As Byte) As String
    		'Algorithm to convert bytes to desired string format
    	End Function
    	
    	Public Function GetInt32String(ByVal value As Int32) As String
    		'Algorithm to convert Int32 to desired string format
    	End Function
    	
    End Module
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | HtmlLessons | CssLessons | Code Tags | Sword of Fury - Jameram

  6. #6

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2007
    Location
    cobwebbed to PC
    Posts
    311

    Re: Overload ToString for Byte array

    I will try that out dday9, and also maybe try the extension option as well, thanks both!

    damnit dday9, thats twice I've tried to squash your signature with my hand!!
    Thanks

  7. #7
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,109

    Re: [RESOLVED] Overload ToString for Byte array

    What's really fun is when you have scrolled one of his posts to the point where that bug just barely wanders into the top of your screen from time to time.
    My usual boring signature: Nothing

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width