Search code examples
c#.netconsole-applicationconsole.writeline

What interface or method should my class implement to print what I want in Console.WriteLine?


I have an object of class F. I want to output the contents of the object using Console.WriteLine for quick and dirty status updates like this:

Console.WriteLine(objectF);

This prints out only the name of the class to the console:

F

I want to overload this somehow so that I can instead print out some useful information about the object and its properties.

I have a workaround already: To overload the ToString method in my class and then call: Console.WriteLine(objectF.ToString());

But I would rather have the simpler syntax. Any ideas?


Solution

  • Console.WriteLine(objectF)

    Should work, if you overloaded ToString. When the framework needs to convert an object to a string representation, it invokes ToString.

    public override string ToString()
    {
        // replace the line below with your code
        return base.ToString();
    }