Reputation: 95
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.
Upvotes: 0
Views: 194
Reputation: 304
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
Upvotes: 1
Reputation: 3185
Use
output += new string(f.contents);
as seen here. Also, consider using a StringBuilder for output
.
Upvotes: 2