is there syntax error in my code

C

C#leaner

I am getting squggly blue on (i==1) as well as on d.


class Program
{
static void Main(string[] args)
{
string d;
int i;
for (i = 0; i < 12; )
{
i++;
if (i == 1) d = "first";
if (i == 2) d = "second";
if (i == 3) d = "third";
if (i == 4) d = "fourth";
if (i == 5) d = "fifth";
if (i == 6) d = "sixth";
if (i == 7) d = "seventh";
if (i == 8) d = "eighth";
if (i == 9) d = "ninth";
if (i == 10) d = "tenth";
if (i == 11) d = "eleventh";
if (i == 12) d = "twelveth";

Console.WriteLine("\nOn the, {0}, day of Christmas", d);
Console.WriteLine("\nmy true love sent to me\n");
switch (d)
{
case "first":
Console.WriteLine("\nA Partridge in a Pear Tree\n");
case "second":
case "third":
case "fourth":
case "fifth":
case "sixth":
case "seventh":
case "eighth":
case "ninth":
case "tenth":
case "eleventh":
case "twelveth":

case "default":
break;
}
i++;

}
}
}
 
M

Mattias Sjögren

Yes there are errors in your code.

You need a break statement (or some other statement that prevents
fallthrough) after the case "first".

You also can't use d in the switch(d) statement because the compiler
can't know for sure that it definitely has been assigned a value. If
you for example initialize d like this, it will take care of that
error.

string d = null;


Mattias
 
J

Jon Skeet [C# MVP]

C#leaner said:
I am getting squggly blue on (i==1) as well as on d.

I don't know why you're getting one on i==1, but using d at the end of
the set of "ifs" is wrong, because it hasn't yet been definitely
assigned a value. I mean, *we* know that one of the "ifs" will have
been true, but the compiler doesn't.

Also, you need a break after the first switch case - you can't fall
through from one case label to another after you've put some code in.
 
C

C#leaner

Jon said:
I don't know why you're getting one on i==1,
Yes, that was really weird. It went awy when I just typed in again and
delted the old one.

but using d at the end of
the set of "ifs" is wrong, because it hasn't yet been definitely
assigned a value. I mean, *we* know that one of the "ifs" will have
been true, but the compiler doesn't.

I was assuming that d was assigned default value initialliy.
Also, you need a break after the first switch case - you can't fall
through from one case label to another after you've put some code in.

I planned to.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top