Can I derive a class from System.Array to override the ToString method?
Posted: (EET/GMT+2)
In the .NET newsgroups, the user "EnerPeter" asked whether it would be possible to derive a new class from an array of bytes (specifically byte[] or more generically System.Array) to override the default ToString() method. Here's my answer almost verbatim.
Unfortunately, the short answer is no. By looking at the documentation for Array, it might appear that you could derive your own types from System.Array, but in fact all (at least all I have used) .NET languages/compilers refuse to allow this. For example, the C# compiler fails with the error message "NN cannot derive from special class System.Array".
However, even if you could do this, deriving would be more difficult than it sounds at first, since the compiler actually does quite a lot of so-called "compiler magic" for you when you use a seemingly simple construct like this:
byte[] myBytes = { 12, 83, 62 };
Since System.Array is an abstract class, the compiler must first create a derived type behind the scenes. Also, there's code needed to initialize the array -- you can see all this when you use ILDASM for example to view the generated MSIL (intermediate language) code.
Finally, if you would derive your own byte array class, it would not work the same as regular arrays. As noted by the MSDN documentation of the Array class:
"However, only the system and compilers can derive explicitly from the Array class. Users should employ the array constructs provided by the language."
So the bottom line is that you cannot do it. With forthcoming C# 3.0 extension methods you could make things look more convenient, but in the end your option is to write some code to convert the byte array to a string. See MSDN for more information about extension methods in C# 3.0.
Finally, here's a simple example of a method that converts a byte array to a proper string:
byte[] myBytes = { 72, 101, 108, 108, 111, 33 };
string str = System.Text.Encoding.ASCII.GetString(myBytes);
MessageBox.Show(str);
This would show: "Hello!". If you wanted to get the real bytes instead, then you could use something like this:
MessageBox.Show(BytesToString(myBytes));
private string BytesToString(byte[] bytes)
{
StringBuilder buffer = new StringBuilder();
buffer.Append("{ ");
foreach (byte b in bytes)
{
if (buffer.Length > 2) buffer.Append(", ");
buffer.Append(b);
}
buffer.Append(" }");
return buffer.ToString();
}
This would show: "{ 72, 101, 108, 108, 111, 33 }".
Hope this helps!