C# Variable is assigned but never used [duplicate] - c#

This question already has answers here:
Variable is assigned but its value is never used (C#)
(4 answers)
Closed 6 years ago.
I am getting an error with my code.. I am new to C# and I am trying to make a two player turn based game. Doing this using visual studio
The error is "Warning 2 The variable 'gs' is assigned but its value is never used"
The code is below;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
namespace GridWorld
{
public class newAI : BasePlayer
{
PlayerWorldState myWorldState;
private double maxSpeed = 5f;
//public int MaxNumTurn = 15;
private int Steps;
private object count;
public newAI ()
: base()
{
this.Name = "AI FOR GAMES THE A TEAM";
// this.MaxNumTurn = 15;
var gs = new GridSquare.ContentType(); // the variable gs is now a new GridSquare content type
}
void Pathfind()
{
PlayerWorldState startingPoint = BasePlayer(GridSquare.ContentType.Snail);
int myX = 0;
int myY = 0;
if (myX == -1 || myY == -1) // if myX & myY are equal to minus 1 then increment the steps
Steps++;
{
return;
}
gs [myX, myY].Steps = 0; // outside whileloop
while (true)
{
bool madeProgress = false;
foreach (startingPoint mainPoint in gs)
{
int x = mainPoint.X;
int y = mainPoint.Y;
if (SquareOpen(x, y))
{
int passHere = GridSquare[x, y].Steps;
foreach (startingPoint movePoint in ValidMoves(x, y))
{
int myX = movePoint.X;
int myY = movePoint.Y;
int newPass = passHere + 1;
if (GridSquare[myX, myY].Steps > newPass)
{
GridSquare[myX, myY].Steps = newPass;
madeProgress = true;
}

It is not really an error. As it says, its just a warning stating that the variable 'gs' is assigned somewhere but never used anywhere. This should not cause your application to stop working.

You're declaring and defining gs in your constructor newAI and attempting to use it in Pathfind. Pathfind can't see it, because it's local to your class constructor i.e. a local scoped variable. Move it into your class like your maxSpeed, Steps and count variables.
It is only a warning, but your code is going to have undefined behaviour at the very least.

Related

Scope issue in function, local variable not defined [duplicate]

This question already has answers here:
C#: Use of unassigned local variable, using a foreach and if
(6 answers)
Closed 4 years ago.
I am getting an error for dateClose.closing, "use is unassigned local variable". I declared dateClose outside of the for loop and defined the value inside the for loop. How can I make that value available outside of the for loop?
public class SMA
{
public Models.DateClose SMAMethod (Queue<Models.DateClose> queue, int period)
{
decimal average, sum=0;
Models.DateClose dateClose;
for (int i = 0; i < period; i++)
{
dateClose = queue.Dequeue();
sum += dateClose.Close;
}
average = sum/period;
dateClose.Close = average; <--- error
return dateClose;
}
}
you can simply fix the error by doing
Models.DateClose dateClose = null;
however you would also want to add a null check to make sure you don't run into null ref exception if queue has no item.
You can do this. If your period variable is greater than the queue count than dateClose.Close will throw an exception.
public Models.DateClose SMAMethod (Queue<Models.DateClose> queue, int period)
{
decimal average, sum=0;
Models.DateClose dateClose = null;
for (int i = 0; i < period; i++)
{
dateClose = queue.Dequeue();
if(dateClose != null)
sum += dateClose.Close;
}
average = sum/period;
dateClose.Close = average;
return dateClose;
}
Why do you get this error:
if you have the class, member variables neednot be initialized:
public class Test
{
private int temp; // this is okay.
..
}
However, if you have a local variable, then you need to initialize them:
public void Method()
{
int variabl;
sum += variable; // error.
}
So, local variables need to be initialized but member variables neednt be.

Calling C# static method from F#

I have this class in C#:
using System.Collections.Generic;
namespace StrassGlassLib
{
public class Mesh
{
private List<Model.Node> _ns;
private List<Model.Plate> _ps;
public Mesh()
{
_ns = new List<Model.Node>();
_ps = new List<Model.Plate>();
}
public List<Model.Node> Nodes => _ns;
public List<Model.Plate> Plates => _ps;
public void AddNode(Model.Node n)
{
_ns.Add(n);
}
public void AddPlate(Model.Plate p)
{
_ps.Add(p);
}
// CREATION METHOD
public static Mesh CreatePlanarMesh()
{
// create new mesh
Mesh m = new Mesh();
// add node
for (int y = 0; y < 2; y += 1)
{
for (int x = 0; x < 4; x += 1)
{
m.AddNode(new Model.Node(0, x, y, 0.0));
}
}
return m;
}
}
}
I'm trying to call from F# to learn how to make test with this language, but:
namespace StraussGlassTest
open System
module MeshTesting =
open StrassGlassLib
let m = Mesh.CreatePlanarMesh()
The problems are:
I've got error FS0039: The namespace or module 'Mesh' is not defined.
No error on the console, the code looks good
if I try to access to Nodes property I've got error FS0039: The field, constructor or member 'Nodes' is not defined
I imagine i miss more than something on how F# works, Do you have some hints?
ok
the problem was the interactive part
#if INTERACTIVE
#r #"C:\Users\p.cappelletto\Documents\Visual Studio 2015\Projects\StraussGlass\StraussGlassLib\bin\Debug\StraussGlassLib.dll"
#r #"C:\Users\p.cappelletto\Documents\Visual Studio 2015\Projects\StraussGlass\StraussGlassLib\bin\Debug\StrausLib.dll"
#endif
namespace StraussGlassTest
open System
module MeshTesting =
open StraussGlassLib
open StrausLib
let m = Mesh.CreatePlanarMesh()
printfn "%A" m.Nodes.Count
Now it works, see it also this

Class Wide Array in C#

I'm trying to create a class wide array in C#, in a Windows Mobile Phone 8.1 project, so that when I create a method I can
What I did at first was:
public sealed partial class GamePage : Page
{
int Score = 0;
int count = 0;
private DispatcherTimer Timer;
public ColorsClass color = new ColorsClass();
public int RandBlue = 0;
int RandGreen = 0;
int RandRed = 0;
int RandYellow = 0;
int RandPurple = 0;
int RandYellowGreen = 0;
int RandOrange = 0;
int RandGray = 0;
bool Equal = true;
int Fail;
int Hit;
int Lives = 10;
Rectangle[] Block = { Block01, Block02, Block03, Block04, Block05, Block06, Block07, Block08, Block09, Block10, Block11, Block12 };
int[] RandomColors = { RandBlue, RandGreen, RandRed, RandYellow, RandPurple, RandYellowGreen, RandGray };
...
}
But it gives me the message that "a field initializer cannot reference the non-static field, method or property..."
Then I tried this option, that I saw when I was search in the internet:
public sealed partial class GamePage : Page
{
int Score = 0;
int count = 0;
private DispatcherTimer Timer;
public ColorsClass color = new ColorsClass();
public int RandBlue = 0;
int RandGreen = 0;
int RandRed = 0;
int RandYellow = 0;
int RandPurple = 0;
int RandYellowGreen = 0;
int RandOrange = 0;
int RandGray = 0;
bool Equal = true;
int Fail;
int Hit;
int Lives = 10;
int []
Random rand = new Random();
public GamePage()
{
this.InitializeComponent();
DispatchTheTime();
RandomColors = new int[] { RandBlue, RandGreen, RandRed, RandYellow, RandPurple, RandYellowGreen, RandGray };
...
}
This way I can reach the array through the methods I created, but the array values are always null..
What can I do?
Everytime when you create a new GamePage you are filling your array with the content of the variables RandGreen, RandRed, ...
At this time, these variables are set to 0. Thus your array contains only 0s. Even if you later assign other values to RandGreen, RandRed, ... the values within the array will not change.
I hope this example will make it clearer:
RandBlue = 0;
var RandomColors = new int[] { RandBlue, RandGreen };
// RandColors[0] is 0
RandBlue = 5;
// RandColors[0] is still 0
Edit:
The error message "a field initializer cannot reference the non-static field, method or property..." should be self-explaining. You could make your color variables const in order to make it work. But I suppose this would not make any sense for you.
Keep in mind that integers are valuetypes. If you create an array of integers like with the RandomColors, you'll just put a copy of your value in the array. At this point, RandGreen and RandomColors[1] point to different memory locations and a change of either won't propagate to the other.
You have to decide whether you want to keep your values in a lot of fields like you actually declared or if you want to keep your integers in an array.
You are propably better off using a Dictionary for your usecase and only access the integers from there.
On class level declare your RandomColors:
Dictionary<string, int> RandomColors = new Dictionary<string, int>();
public GamePage()
{
RandomColors.Add("RandGreen", 0);
RandomColors.Add("RandRed", 0);
//change like this:
RandomColors["RandGreen"] = 5;
//access like this:
int x = RandomColors["RandGreen"];
}

Nested Loop not iterating

In my code I have a nested loop which does not iterate with the exception of an if statement that always occurs no matter what the condition. Without the if statement the portion of the for loop's code which iterates the loop becomes unreachable. No matter what I have tried I have not been able to get the inside loop to iterate.
class Map
{
public int Width { get; set; }
public int Height { get; set; }
public Vector2[] positions = new Vector2[500*500];
private GroundVoxel[,] map = new GroundVoxel[500, 500];
private Vector2 voxelPosition = new Vector2(0,0);
private static int sizeX = 499, sizeY = 499, airLevel = 425;
private int positionX = 0, positionY = 0, vectorNumber = 0;
public Map()
{
}
public Vector2[] Initialize()
{
for (int i = 0; i <= sizeY; i++)
{
for (int j = 0; j <= sizeX; j++) <-- This does not iterate.
{
map[positionX, positionY] = new GroundVoxel(voxelPosition);
voxelPosition.X += 80;
positions[vectorNumber] = voxelPosition;
vectorNumber += 1;
if (j == sizeX) <-- This always executes even though j != sizeX.
{
break;
}
}
voxelPosition.Y += 80;
voxelPosition.X = 0;
}
return positions;
}
}
}
You have to use the fully qualified name to refer to a static class member variable like your sizeX and sizeY. Here is an article on the subject.
Hope this helps!
I think we'll need more code. I've copied your code into a basic winforms test application and both of my loops iterates as expected.
I'm not familiar with XNA or what a "VoxelPosition" is, but I think you have a lurking bug here:
voxelPosition.X += 80;
positions[vectorNumber] = voxelPosition;
You are simply storing the same pointer in a very large array -- all of the entries will be pointing to the same object.
You will need to declare another object every time through the loop to store individal vector entries.
Hope this helps?

My first c# app and first null object exception

Total noob here. This is my first c# attempt, its a console application that simulates a drinking game called 'Left Right Center'. In the console I receive the following:
CONSOLE
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object
at LeftRightCenter.MainClass.Main (System.String[] args) [0x00038] in /Users/apple/Projects/LearningC/LearningC/Main.cs:80
[ERROR] FATAL UNHANDLED EXCEPTION: System.NullReferenceException: Object reference not set to an instance of an object
at LeftRightCenter.MainClass.Main (System.String[] args) [0x00038] in /Users/apple/Projects/LearningC/LearningC/Main.cs:80
C#
using System;
namespace LeftRightCenter
{
class Player
{
//fields
private int _quarters = 4;
public int Quarters {
get{ return _quarters; }
set{ _quarters += value; }
}
public Player (string name)
{
}
}
class Dice
{
Random random = new Random();
public int Roll ()
{
random = new Random ();
int diceSide;
diceSide = random.Next (0, 6);
diceSide = (diceSide > 2) ? 3 : diceSide;
return diceSide;
}
}
class MainClass
{
static int activePlayer = 0;
static int theCup = 0;
static Player[] thePlayers = {
new Player ("Jessica"),
new Player ("Isaac"),
new Player ("Ed"),
new Player ("Bella"),
new Player ("Elisa"),
new Player ("Fake RedHead"),
new Player ("Linda"),
new Player ("MJ"),
new Player ("Irene"),
new Player("Devin")
};
static Dice[] theDice = new Dice[2];
private static void MoveQuarter (int direction)
{
int numberOfPlayers = thePlayers.Length - 1;
switch (direction) {
case 0:
thePlayers [activePlayer].Quarters = -1;
theCup++;
break;
case 1:
thePlayers [activePlayer].Quarters = -1;
int leftPlayer = (activePlayer == 0) ? numberOfPlayers : activePlayer - 1;
thePlayers [leftPlayer].Quarters = +1;
break;
case 2:
thePlayers [activePlayer].Quarters = -1;
int rightPlayer = (activePlayer == numberOfPlayers) ? 0 : activePlayer + 1;
thePlayers [rightPlayer].Quarters = +1;
break;
}
}
public static void Main (string[] args)
{
int cupEndPoint = thePlayers.Length * 4 - 1;
while (theCup < cupEndPoint) {
foreach (Dice rattle in theDice) {
if (thePlayers [activePlayer].Quarters > 0) {
MoveQuarter (rattle.Roll ()); // this line seems to be the problem
}
}
Console.WriteLine ("{0} Quarters In the Cup", theCup);
}
}
}
}
I have no idea what the problem is or why, and my googling have proven more use confusing than helpful.
For those who are curious, I have little experiment working now
http://pastebin.com/jxCCW2cd
This line
static Dice[] theDice = new Dice[2];
declares an array that allows the storage of 2 objects of the Dice class, but each value in this array is still null.
You need to create a Dice on each slot of the array before using it in the foreach loop inside the Main method.
theDice[0] = new Dice();
theDice[1] = new Dice();
if you stop the debugger on the line
MoveQuarter (rattle.Roll ());
you will see that the rattle Dice is null.
EDIT: Looking at your code I have found a problematic situations
In the Roll method, you recreate the Random generator and this is no good for randomness. (See the accepted answer in this question)
Last, theDice array could be created and initialized in the same way you already do for thePlayers array
static Dice[] theDice = new Dice[2] {new Dice(), new Dice()};
This is a complete revision of your Dice class
class Dice
{
private static Random random;
public Dice()
{
// create the static random generator only on the first instance
if(random == null) random = new Random();
}
public int Roll ()
{
int diceSide;
diceSide = random.Next (1, 7);
diceSide = (diceSide > 2) ? 3 : diceSide;
return diceSide;
}
}

Categories

Resources