DethoRhyne DethoRhyne - 2 months ago 8
C# Question

How to change default custom class output

Here's what I'm trying to get at:

System.String
is a
class
that contains an array of characters and if we were to make a string and then print it out:

String text = "Hello world!";
Console.WriteLine(text);


the output would be Hello World!

Now lets say I made my own
class
:

public class Output
{
string aProperty;
int Count;
...
}


and if I were to create a
new object
of that type and try to write it out:

Output output = new Output();
Console.WriteLine(output);


I would get this back:

Namespace.Output


How could I change this so it always prints the content of
Output.aProperty
instead of the default text?

Answer

WriteLine method simply writes what the ToString of the object returns. ToString is defined (as virtual) in Object class, so you need to override it to have a "custom" output:

public class Output 
{
    string aProperty;
    int Count;

    public override string ToString()
    {
        return string.Format("{0}: {1}", aProperty, Count);//Or whatever you want
    }
}