Reputation: 21
(I'm a beginner and just started learning C# in college/A-level, so my code is really inefficient).
Anyway, the code below is just a part of my "CinemaBookingSystem" and because my variable filmName is declared outside of my switch case, it says that "filmName" does not do not exist in this context. I tried using the "public static string filmname = "example";" method but that won't work because I'm declaring filmname more than once inside different if statements.
if (filmNum == 1)
string filmName = "Teenage Horror Film";
if (filmNum == 2)
;
string filmName = "How I Live Now";
switch (filmNum)
{
case 1:
case 2:
if (Age >= 15)
{
Console.WriteLine("What date do you want to watch the film? (Format : dd/mm/yyyy) :");
DateTime dateChoice = DateTime.Parse(Console.ReadLine());
DateTime now = DateTime.Now;
DateTime limit = now.AddDays(7);
if (dateChoice >= now && dateChoice <= limit)
{
Console.WriteLine("--------------------");
Console.WriteLine("Aquinas Multiplex");
Console.WriteLine("Film : {0}", filmName);
Console.WriteLine("Date : {0}", dateChoice);
Console.WriteLine("--------------------");
}
else
{
Console.WriteLine("Access denied - date is invalid");
}
}
while (Age < 15)
{
Console.WriteLine("Access denied - You are too young");
}
break;
}
Upvotes: 1
Views: 1078
Reputation: 24
You need to declare it outside of the if statements and just asign the value inside (make sure there is a default value in case neither if gets triggered). Also you have semicolons right behind your if statements.
Upvotes: 1
Reputation: 6010
Kenny, since you declare variable filmName
in condition statement it is not accessible in switch
. You need to declare it before if
:
string filmName = string.empty;
if (filmNum == 1) ;
{
filmName = "Teenage Horror Film";
}
if (filmNum == 2) ;
{
filmName = "How I Live Now";
}
switch (filmNum)
{
case 1: case 2:
if (Age >= 15)
{
Console.WriteLine("What date do you want to watch the film? (Format : dd/mm/yyyy) :");
DateTime dateChoice = DateTime.Parse(Console.ReadLine());
DateTime now = DateTime.Now;
DateTime limit = now.AddDays(7);
if (dateChoice >= now && dateChoice <= limit)
{
Console.WriteLine("--------------------");
Console.WriteLine("Aquinas Multiplex");
Console.WriteLine("Film : {0}", filmName);
Console.WriteLine("Date : {0}", dateChoice);
Console.WriteLine("--------------------");
}
else
{
Console.WriteLine("Access denied - date is invalid");
}
}
while (Age < 15)
{
Console.WriteLine("Access denied - You are too young");
}
break;
}
}
}
Upvotes: 1