Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime in .NET

Tags:

c#

.net

To get the time and date from system why do I need System.DateTime.Now ? As you can see there is a System namespace already declared at the top. If I just write DateTime.Now it doesn't work. I learned earlier that If we declare "using System" then we don't have to declare or write System.Console.WriteLine or System.DateTime.Now etc.

using System;
using System.Text;

namespace DateTime
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("The current date and time is " + System.DateTime.Now);
        }
    }
}
like image 676
Jasmine Appelblad Avatar asked Dec 10 '22 12:12

Jasmine Appelblad


1 Answers

It's because your namespace is already called DateTime which clashes with an existing class name. So you could either:

namespace DateTime
{
    using System;
    using System.Text;

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("The current date and time is " + DateTime.Now);
        }
    }
}

or find a better naming convention for you own namespaces which is what I would recommend you doing:

using System;
using System.Text;

namespace MySuperApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("The current date and time is " + DateTime.Now);
        }
    }
}
like image 188
Darin Dimitrov Avatar answered Dec 26 '22 05:12

Darin Dimitrov