Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Console.Writeline basics

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?

like image 457
CuriousGuy Avatar asked May 23 '15 14:05

CuriousGuy


People also ask

How does console WriteLine work?

WriteLine(String, Object, Object) Writes the text representation of the specified objects, followed by the current line terminator, to the standard output stream using the specified format information.

What is difference between write () and WriteLine ()?

The only difference between the write() and writelines() is that write() is used to write a string to an already opened file while writelines() method is used to write a list of strings in an opened file.

What does 0 mean in console WriteLine?

And {0} Is a formatted message, When you define It to {0} It means printing/formatting the zero Index object that you Inserted Into params arguments of your function. It's a zero based number that gets the index of object you want, Here's an example: Console.

How do you write a console message in C#?

In C# you can write or print to console using Console. WriteLine() or Console. Write(), basically both methods are used to print output of console.


2 Answers

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".

like image 125
Yuval Itzchakov Avatar answered Oct 21 '22 12:10

Yuval Itzchakov


Since there is no overload for Console.WriteLine(DateTime),as in your case,the Console.WriteLine(Object) overload is called and this overload calls the TextWriter.WriteLine(object) overload which is implemented as:

IFormattable f = value as IFormattable;
if (f != null)
    WriteLine(f.ToString(null, FormatProvider));
else
    WriteLine(value.ToString());

As you can see, this method checks if this object type implements IFormattable interface or not. Since Datetime implements this interface, your f.ToString(null, FormatProvider) will be called. From this method's documentation the first parameter is:

A null reference (Nothing in Visual Basic) to use the default format defined for the type of the IFormattable implementation.

And from the DateTime.ToString(String, IFormatProvider) method's documentation:

If format is null or an empty string (""), the standard format specifier, "G"., is used.

That means, the representation will be a combination of the ShortDatePattern and LongTimePattern properties belonging to your CurrentCulture

If you want a special format for your custom class, you can override the .ToString() method of your type to change its behaviour.

like image 30
Soner Gönül Avatar answered Oct 21 '22 13:10

Soner Gönül