0

I have a class, Record, and within that class is an array of objects (fields). Ideally, I want to be able to call Record.ToString() and have that return to me the ToString() of every Field in the fields array. The Field class contains a charArray.

class Record
{
    class Field
    {
        public char[] contents;
        public Field(int size)
        {
            contents = new char[size];
        }
    }
    public Field[] fields;
    public Record()
    {
        fields = new Field[4];
        foreach(Field f in fields)
            f = new Field(4);
    }
    public override string ToString()
    {
        string output = null;
        foreach(Field f in fields)
            output += f.contents.ToString();
        return output;
    }
}

Note; I have not posted all my code, but I do have initialize functions that fill the contents char[] so they are not empty.

For some reason, calling Record.ToString() returns System.Char[]. I do have an instance of Record, and have tried this multiple different ways, including overriding ToString() in the Field class, to return contents.ToString(), but it gives me the same output. The strangest thing is,

System.Console.WriteLine(Record.fields[x].contents);

gives me the string contained inside contents.

Jesse Fogel
  • 75
  • 2
  • 10

2 Answers2

2

Use

output += new string(f.contents);

as seen here. Also, consider using a StringBuilder for output.

Community
  • 1
  • 1
PhilMasteG
  • 3,095
  • 1
  • 20
  • 27
1

You are returning the char[] when you call f.contents.ToString(); not the contents of the contents. If you want return what is in the contents, then you will either have to iterate through f.contents[], or use what Phillip Grassl has posted, that will use the char[] and make a string out of them.

f.contents.ToString() = char[];

new string(f.contents) = char[0] + char[1] + char[2] + char[3] . . . etc

Seige
  • 304
  • 5
  • 27
  • awesome, thank you! I do have a question though, why does it work when I call? System.Console.WriteLine(Record.fields[x].contents); – Jesse Fogel Aug 23 '15 at 21:19
  • That is a good question that I'm sure someone who knows more than me would know. But I believe magic. Possibly the console doing something because it doesn't like arrays? Because it is being passed the entire array, not the ToString() value – Seige Aug 23 '15 at 21:22
  • Indeed, though it will work if you call contents.ToString() as well – Jesse Fogel Aug 23 '15 at 21:38
  • Thats because System.Console.WriteLine() has an extra overload that takes a char[] and outputs that correctly. See here: https://msdn.microsoft.com/en-us/library/system.console.writeline%28v=vs.110%29.aspx – PhilMasteG Aug 23 '15 at 21:48