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!