Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change default custom class output [duplicate]

Tags:

c#

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?

like image 739
DethoRhyne Avatar asked Dec 08 '25 07:12

DethoRhyne


1 Answers

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
    }
}
like image 135
Matteo Umili Avatar answered Dec 09 '25 22:12

Matteo Umili



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!