Search code examples
c#consoleintvarconsole.writeline

How can I write these variables into one line of code in C#?


I am new to C#, literally on page 50, and i am curious as to how to write these variables in one line of code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace consoleHelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {

            int mon = DateTime.Today.Month;
            int da = DateTime.Today.Day;
            int yer = DateTime.Today.Year;
            var time = DateTime.Now;

            Console.Write(mon);
            Console.Write("." + da);
            Console.WriteLine("." + yer);
        }
    }
}

I am coming from JavaScript where to do this it would look like this:

document.write(mon+'.'+da+'.'+yer);

Any help here is appreciated.


Solution

  • Look into composite formatting:

    Console.WriteLine("{0}.{1}.{2}", mon, da, yer);
    

    You could also write (although it's not really recommended):

    Console.WriteLine(mon + "." + da + "." + yer);
    

    And, with the release of C# 6.0, you have string interpolation expressions:

    Console.WriteLine($"{mon}.{da}.{yer}");  // note the $ prefix.