I have a class that primarily provides a 2d array to its caller (after parsing a file). It's returning this array fine, but I need to provide a way for that caller to convert that 2d array to a multi-delimited string. pseudocode below.
Full disclosure: Most of my time is scripting in other software, so I'm a bit rusty on OOP in reality, and especially in c#
I want the caller to be able to:
string[,] results;
getArray (arg1, arg2, etc, out results);
Debug.WriteLine(results.ToString(delim1, delim2));
but I'm not clear on how to create this override for ToString(), something like:
public override string[,] ToString(string rowSeparator, string columnSeparator)
{
string retVal = "";
for(int r = 0; r < this.getUpperBound(0); r ++)
{
for (int c = 0; c < this.getUpperBound(1); c++)
{
retVal += this[r,c];
if (c + 1 < this.getUpperBound(1))
{
retVal += columnSeparator;
}
}
if (r + 1 < this.getUpperBound(0))
{
retVal += rowSeparator;
}
}
return retVal;
}
That's not overriding anything - you're trying to overload the existing ToString
method. It's a good job you're not trying to override anything, as you basically can't do that - you can only override members within a class declaration, and you can't declare the string[,]
class yourself.
You can achieve your goal with an extension method:
public static class ArrayExtensions
{
public static string ToString(
this string[,] array, string rowSeparator, string columnSeparator)
{
// Code as per your method, but using array instead of this
}
}
Note that callers will need to have a using
directive for the namespace containing ArrayExtensions
, or a using static
directive for the ArrayExtensions
class itself, in order to use this as an extension method.
I'd also recommend using StringBuilder
in your implementation instead of repeated string concatenation.
See more on this question at Stackoverflow