Console.Writeline basics

CuriousGuy picture CuriousGuy · May 23, 2015 · Viewed 10.1k times · Source

I have a question about the following code:

class CurrentDate
    {
        static void Main()
        {
            Console.WriteLine(DateTime.Now);
        }
    }

Documentation says:

Writes the text representation of the specified array of objects, followed by the current line terminator, to the standard output stream using the specified format information.

So my question is: How come WriteLine knows the text representation of DateTime object? I mean, if I create my own object from my own class, how would it know how to convert the value to text? And even more, how does it know what the value is? How can you define "value" of an object?

Answer

Yuval Itzchakov picture Yuval Itzchakov · May 23, 2015

How come WriteLine knows the text representation of DateTime object? I mean, if I create my own object from my own class, how would it know how to convert the value to text?

Console.WriteLine has a set of overloads matching specific types (mainly primitives). If the compiler doesn't match an overload with the provided type, it matches with the overload taking System.Object (granted you provide a single parameter). If that happens, it checks to see if the type implements IFormattable, if it does, it invokes IFormattable.ToString(null, Formatter). If it doesn't, it invokes ToString on your object. ToString is defined in System.Object , which all objects inherit from. Every object that wants a custom representation overrides the default behavior, like DateTime does.

For example, lets say you have a Foo class with a Bar string property, and you want Console.WriteLine to print something meaningful when passing your Foo to it:

public class Foo
{
    public string Bar { get; set; }
    public override string ToString()
    {
         return Bar;
    }
}

And now we want to pass it Console.WriteLine:

public static void Main(string[] args)
{
      var foo = new Foo { Bar = "bar" };
      Console.WriteLine(foo);
}

Would yield "bar".