1

Let's say I have an array of custom type, and I put in it 10 objects of custom struct type. CustomType[] Record = new CustomType[10];

Now since each CustomType has fields, I can assign the fields for each element of CustomType in the array. For example:

Record[0].name = "John";
Record[0].age = 34;

And there is the ToString() method, which in usual types like int or string, turns the value of the type to string. So if we had

someIntArray[0] = 32;
Console.WriteLine(someIntArray[0].ToString());

Then we would get the output "32" on the console, not its value type, int.

But if we use the same method on the above example with the CustomType array, and write:

Console.WriteLine(Record[0].ToString());

Then we won't get the value(s) that the object contains (in its fields), but the type of it. Of course I could write for example:

Console.WriteLine(Record[0].name + Record[0].age);

But you can see how if the struct has many fields this gets old and tedious very fast. And especially if you don't want to just print out all the fields of just one struct object, but all of the struct objects in the array.

So here is my question: Is there a method in .NET, or some other easy way so I can manipulate (e.g. print) all the fields of an array element like a struct in a simpler, faster way ?

2 Answers2

1

I think people assume that structs can't contain methods, but they absolutely can! Just create a ToString() method.

ScoobyDrew18
  • 633
  • 9
  • 20
0

You can still override ToString() in a struct!

struct Record
{
    string name;
    int age;

    public override string ToString()
    {
        return String.Format("{0} {1}", record.name, record.age);
    }

}

You thus do not have to explicitly call it:

Console.WriteLine(record); // e.g., Joe 5
gnalck
  • 972
  • 6
  • 12
  • 1
    You can override ToString() on a struct. http://stackoverflow.com/questions/1249086/boxing-on-structs-when-calling-tostring – ScoobyDrew18 Apr 06 '16 at 23:09
  • Oh, cool. I looked at this link to confirm: http://zetcode.com/lang/csharp/structures/ . Ill update my answer. – gnalck Apr 06 '16 at 23:12
  • Thank you! How I didn't I thought of this earlier ? It was in plain site. I guess you can't have though a more generalized method that will work with each struct, and one will have to format the string adding the names of the fields each time for each different struct eh ? –  Apr 06 '16 at 23:15
  • @StavrosD It is possible to dynamically print out an entire object in C#. Look at http://stackoverflow.com/questions/852181/c-printing-all-properties-of-an-object – gnalck Apr 06 '16 at 23:22