Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 854
Erik Grosskurth Avatar asked Mar 14 '13 19:03

Erik Grosskurth


People also ask

How do I declare multiple variables in one line in C#?

In c#, we can declare and initialize multiple variables of the same data type in a single line by separating with a comma. Following is the example of defining the multiple variables of the same data type in a single line by separating with a comma in the c# programming language.

What is console WriteLine () good for?

Write is used to print data without printing the new line, while Console. WriteLine is used to print data along with printing the new line.


2 Answers

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. 
like image 85
Jim Mischel Avatar answered Sep 27 '22 22:09

Jim Mischel


You can do your whole program in one line! Yes, that is right, one line!

Console.WriteLine(DateTime.Now.ToString("yyyy.MM.dd")); 

You may notice that I did not use the same date format as you. That is because you should use the International Date Format as described in this W3C document. Every time you don't use it, somewhere a cute little animal dies.

like image 32
Malcolm O'Hare Avatar answered Sep 27 '22 22:09

Malcolm O'Hare