Question by
alexwong817 · Aug 02, 2016 at 02:34 PM ·
c#parsing errorunexpected-symbol
Parser Error - Unexpected symbol
I am new with c# and I've been working on a simple program but seems there is something wrong that causes a "Parser Error" keeps showing up. I don't understand the error. Any help?
Program.cs
using System;
namespace CounterTest
{
class MainClass
{
Counter[] counters;
private static void PrintCounters(Counter [] counters)
{
Counter[] _c = counters;
foreach(_c in counters)
{
}
}
public static void Main (string[] args)
{
//Console.Write ("Welcome");
Counter[] myCounters = new Counter[3]; // an array of 3 references to Counter objects
int _i;
myCounters [0] = new Counter ("Counter 1");
myCounters [1] = new Counter ("Counter 2");
myCounters [2] = myCounters [0];
for(_i=0; _i<4; _i++)
{
//Tell myCounter[0] to Increment
myCounters[0].Increment();
}
for(_i=0; _i<9; _i++)
{
//Tell myCounter[1] to Increment
myCounters[1].Increment();
}
//PrintCounters
}
}
}
Counter.cs:
using System;
namespace CounterTest
{
public class Counter
{
private int _count;
private string _name;
public Counter (string name)
{
_name = name;
_count = 0;
}
// Increment method
public void Increment()
{
_count++;
}
// Reset method
public void Reset()
{
_count = 0;
}
// Create a Name property
public string Name
{
set
{
_name = value;
}
get
{
return _name;
}
}
// Creaste a Value property
public int Value
{
get
{
return _count;
}
}
}
}
screen-shot-2016-08-03-at-010530.png
(326.3 kB)
Comment
Best Answer
Answer by Landern · Aug 02, 2016 at 03:09 PM
You need to specify the type in the foreach or use var to have the compile use type inference.
// Explicit
foreach(Counter _c in counters)
{
}
// type inference
foreach(var _c in counters)
{
}
For each element in the collection(array) it needs to know what each type is in "counters", particularly if this is a custom type with custom members.
no and it makes it more confusing since you're using that same named field from the class, i would remove line 11
Answer by adriono · Aug 02, 2016 at 03:50 PM
Add type Counter
before _c
in 13th line:
foreach(Counter _c in counters)
Your answer
![](https://koobas.hobune.stream/wayback/20220612090024im_/https://answers.unity.com/themes/thub/images/avi.jpg)