user6666700
user6666700

Reputation: 39

Implicitly-typed variables must be initialized

using System;

namespace Task2
{
    class BirthDate
    {
        static void Main(string[] date)
        {
            var Month;
            Console.WriteLine("Please enter your month of birth:");
            Month = Console.ReadLine();

            var Day;
            Console.WriteLine("Please enter your day of birth:");
            Day = Console.ReadLine();

            Console.WriteLine("Your birth month is {0}, on day {1}", Month, Day);


            Console.ReadLine();
        }
    }
}

When i try to compile, I get two errors from the variables and I'm not sure how to fix it.

Upvotes: 3

Views: 12466

Answers (4)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

When you put just

 var Day;

the compiler can't figure out Day variable's actual type; change it to

 var Day = Console.ReadLine();

and having known that Console.ReadLine() returns String, the compiler can easily detect that Day is of type String:

 Console.WriteLine("Please enter your month of birth:");
 var Month = Console.ReadLine();

 Console.WriteLine("Please enter your day of birth:");
 var Day = Console.ReadLine(); 

Upvotes: 4

Shreevardhan
Shreevardhan

Reputation: 12641

Either let compiler infer the type from assignment

Console.WriteLine("Please enter your month of birth:");
var Month = Console.ReadLine();

Or specify the type explicitly

string Month;
Console.WriteLine("Please enter your month of birth:");
Month = Console.ReadLine();

Upvotes: 1

MichaelThePotato
MichaelThePotato

Reputation: 1525

You haven't define which type Month and Day are. when using "var" you have to set a value to it upon definition. the easiest way to fix your code is to simply write var before the console read as such:

using System;

namespace Task2
{
    class BirthDate
    {
       static void Main(string[] date)
       {
           Console.WriteLine("Please enter your month of birth:");
           var Month = Console.ReadLine();
           Console.WriteLine("Please enter your day of birth:");
           var Day = Console.ReadLine();
           Console.WriteLine("Your birth month is {0}, on day {1}", Month, Day);
           Console.ReadLine();
       }
    }
}

Upvotes: 0

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33381

You can't use implicitly typed variable without initialization. You should initialize the variabe to let compiler to infer type of variable.

Don't use inplicitly typed variables when type of variable not obvious when looking on code.

var iDontKnowWhatTypeOfIt = SomeMethod();  // not good

var itIsObviousThatImTimeSpan = TimeSpan.FromSeconds(5); // OK

Upvotes: 1

Related Questions