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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With