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.

2 Answers 2

2

Use

output += new string(f.contents); 

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

Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

awesome, thank you! I do have a question though, why does it work when I call? System.Console.WriteLine(Record.fields[x].contents);
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
Indeed, though it will work if you call contents.ToString() as well
Thats because System.Console.WriteLine() has an extra overload that takes a char[] and outputs that correctly. See here: msdn.microsoft.com/en-us/library/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.