- Home /
Error CS0135 switch enum from other class
Hi all, i have the following error with this code : error CS0135: "stat" conflicts with a declaration in a child block
[System.Serializable]
public class stat
{
public enum typeStat { GameStat, RoundStat };
public string statName;
public typeStat statType;
public float statValue;
}
public List<stat> listGameStats = new List<stat>();
public List<stat> listRoundStats = new List<stat>();
public void incrementeStatValue(string statName, stat.typeStat statType)
{
switch (statType){
case stat.typeStat.GameStat:
listGameStats.Where(stat => stat.statName == statName).ToList()[0].statValue += 1;
break;
case stat.typeStat.RoundStat:
listRoundStats.Where(stat => stat.statName == statName).ToList()[0].statValue += 1;
break;
}
}
The code give me the error on the case line for stat.typeStat.GameStat and stat.typeStat.GameStat and i really dont understand why.The error exist in "editor time" so it's not a probleme with the data in my lists .Someone have an idea?
Answer by EDevJogos · Jun 29, 2016 at 07:53 PM
You are creating a local variable called stat in your method, and your class is also called stat, so it generates a conflict.
public class stat{
Then on your method you have this: listGameStats.Where(stat =>
stat in this where is the variable that will recieve the current value of the enumerator listGameStats.Where
Answer by Bunny83 · Jun 29, 2016 at 07:05 PM
Your lambda expression uses the name "stat" as parameter name. This conflicts with the type "stat". Use a different parameter name:
listGameStats.Where(s => s.statName == statName).FirstOrDefault.statValue += 1;
Note that i changed your "ToList" to "FirstOrDefault". This doesn't create unnecessary overhead. But keep in mind that any variant will create an error if no "stat" with the given name is found. Your variant would generate an index out of bounds since you try to access element "0" which will fail if there is no element.
My variant would throw a NullReference exception since FirstOrDefault returns "null" (the default value) if there's no element in the enumeration. It's better to do something like this:
public void incrementeStatValue(string statName, stat.typeStat statType)
{
List<stat> list;
switch (statType){
case stat.typeStat.GameStat:
list = listGameStats;
break;
case stat.typeStat.RoundStat:
list = listRoundStats;
break;
}
if (list == null)
return;
stat item = list.Where(s => s.statName == statName).FirstOrDefault;
if (item != null)
item.statValue += 1;
}
This variant will be safe in all situations (given that the list do not contain null elements).
Thx i'm blind sometimes... I will do the change for firstordefault, it will be better.
Your answer
Follow this Question
Related Questions
How to check if an enum’s case has changed 3 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
C# Enum for Animation Issue 1 Answer
Enum has "Unknown resolve error" 1 Answer