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

10

33

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.

Britney answered 14/3, 2013 at 19:28 Comment(0)
H
72

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.
Healthy answered 14/3, 2013 at 19:29 Comment(8)
why is the second way not recommended?Fling
OK great! Thanks I haven't gotten to composite formatting. but I was not closing the ToString with () thus the issue. I am still on types right now but this is valuable insight moving forward...Britney
@AStidham: Not recommended because it's longer, more difficult to see what's going on, more difficult to modify, and less amenable to internationalization.Healthy
@Servy: Good catch. I didn't realize that the compiler would do that. Shows you how often I do string concatenation, doesn't it?Healthy
It's not really the compiler. The operator + has three overloads for string concatenation: (string, string), (string, object), and (object, string). The rest of the overloads involve both parameters being numeric types. For the 2nd and 3rd overloads it just calls ToString on the object (after null checking it) in the body of the definition.Canotas
This is ultimately what I was trying earlier and the problem was that if a string is not separating the int's they would add together. This is why I like the top method more. Thanks guys for your inputBritney
I don't have enough rep to do that yet, I have to have 15 points and I only have 11, If you vote up my question then I might have enough to go through them all and up vote themBritney
Just going back looking at old questions and now that i have enough rep I marked it correct. Thanks Jim!Britney
M
17

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.

Maneuver answered 14/3, 2013 at 19:33 Comment(4)
Thanks for that, didn't notice. Will amend this response to chastise him for his poor choice of date format.Apnea
Not just a single line, but a single function call :) Console.WriteLine("{0:yyyy.MM.dd}", DateTime.Now);Leveille
And every time you try to force the International Date Format on a client who wants MM/DD/YYYY, you lose a job.Healthy
for the cute little animals everywhereEnesco
D
8

You can do pretty much the same as in JavaScript. Try this:

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

Or you can use WriteLine as if it were a string.Format statement by doing:

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

which is equivalent to:

string.Format("{0}.{1}.{2}", mon, da, yer);

The number of parameters can be infinite, just make sure you correctly index those numbers (starting at 0).

Disrobe answered 14/3, 2013 at 19:30 Comment(0)
E
5

You should try this one:

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

See http://www.dotnetperls.com/console-writeline for more details.

Endymion answered 14/3, 2013 at 19:30 Comment(0)
E
4

If you want to use something similar to the JavaScript, you just need to convert to strings first:

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

But a (much) better way would be to use the format option:

Console.WriteLine("{0}.{1}.{2}", mon, da, yer);
Engeddi answered 14/3, 2013 at 19:30 Comment(1)
OK great! Thanks I haven't gotten to composite formatting. but I was not closing the ToString with () thus the issue. I am still on types right now but this is valuable insight moving forward...Britney
S
1

You could theoretically do the entire thing as simply:

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

namespace consoleHelloWorld {
class Program {
    static void Main(string[] args) {
       Console.WriteLine(DateTime.Now.ToString("MM.dd.yyyy"));
    }
  }
}
Shunt answered 14/3, 2013 at 19:53 Comment(1)
Yes that's great but I wanted to break up the date and get the numbers individually first then reassemble them but you are absolutely rightBritney
B
1
 DateTime dateTime = dateTime.Today.ToString("MM.dd.yyyy");

 Console.Write(dateTime);
Berlinda answered 11/7, 2013 at 2:24 Comment(0)
E
1

Use $ before " " it will allow to write variables between these brackets

 Console.WriteLine($"{mon}.{da}.{yer}");

The pro way :

  Console.WriteLine($"{DateTime.Today.Month}.{DateTime.Today.Day}.{DateTime.Today.Year}");
  Console.WriteLine($"month{DateTime.Today.Month} day{DateTime.Today.Day} year{DateTime.Today.Year}");

5.24.2016

month5 day24 year2016

Extensible answered 24/5, 2016 at 12:22 Comment(0)
W
0

Give this a go:

string format = "{0} / {1} / {2} {3}";
string date = string.Format(format,mon.ToString(),da.ToString(),yer.ToString();
Console.WriteLine(date);

In fact, there's probably a way to format it automatically without even doing it yourself.

Check out http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

Whop answered 14/3, 2013 at 19:30 Comment(0)
S
0

Simple as:

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

link to MSDN on ALL formatting options for DateTime.ToString() method

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

Siccative answered 14/3, 2013 at 19:34 Comment(1)
This did though: DateTime thisDate1 = DateTime.Now; Console.WriteLine("Today is " + thisDate1.ToString("MMMM dd, yyyy") + ".");Britney

© 2022 - 2024 — McMap. All rights reserved.