Jasmine Appelblad
Jasmine Appelblad

Reputation: 1600

DateTime in .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);
        }
    }
}

Upvotes: 4

Views: 6015

Answers (2)

Josh
Josh

Reputation: 69272

Because your Program class is in a namespace called DateTime. That conflict means the compiler will look for a type called Now in your namespace DateTime which obviously doesn't exist.

Rename your namespace and you won't have the problem.

Upvotes: 3

Darin Dimitrov
Darin Dimitrov

Reputation: 1039328

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);
        }
    }
}

Upvotes: 11

Related Questions