Get; Set; Variables - c#

I'm setting up multiple methods and wondering how to continue to pass one variable (The "top" variable) to different methods.
Main method:
public static void Main(string[] args)
{
int[] anArray = new int[5];
int top = -1;
PushPeek(anArray);
then I need to pass top to:
public static void PushPeek(int[] ar)
{
if (ar[ar.Length -1] == ar.Length -1)
{
//do nothing
}
else
{
top = top + 1;
Console.WriteLine(ar[top]);
}
}\
I know it involves something with get; set; but I don't know how, any help?

Pass it by reference:
public static void PushPeek(int[] ar, ref int top)
{
...
}
int[] anArray = new int[5];
int top = -1;
PushPeek(anArray, ref top);

All about properties: http://msdn.microsoft.com/en-us/library/aa288470(v=vs.71).aspx
Auto-implemented properties are awesome! http://msdn.microsoft.com/en-us/library/bb384054.aspx

Related

Try to display a int through a static field, but return a weird value (C#)

I'm trying to cut down on how much duplication I have on my code, so I decided to make one of my classes a static class since I decided that its data should really be shared with everyone. Here's the static method below:
// A static class, that holds all object's coordinates, and methods to return & update their values.
internal static class Coordinate
{
private static int[,] PlayerCoordinate { get; set; }
public static int[,] GateCoordinate { get; }
public static int[,] FountainCoordinate { get; }
static Coordinate() // FIRST VALUE IS X (column), SECOND VALUE IS Y (row).
{
PlayerCoordinate = new int[,] { { 0, 0 } };
GateCoordinate = PlayerCoordinate; // Just starts off in the same place as player.
FountainCoordinate = new int[,] { { 2, 0 } };
}
// A static method, that sends the data of all object coordinates, deconstructed into seperate ints.
public static int PlayerColumn() { return PlayerCoordinate[0, 0]; }
public static int PlayerRow() { return PlayerCoordinate[0, 1]; }
public static int GateColumn() { return GateCoordinate[0, 0]; }
public static int GateRow() { return GateCoordinate[0, 1]; }
public static int FountainColumn() { return FountainCoordinate[0, 0]; }
public static int FountainRow() { return FountainCoordinate[0, 1]; }
// Updates the coordinates of the player.
public static void UpdatePlayerCoordinate(int column, int row) { PlayerCoordinate = new int[,] { { column, row } }; }
}
The main issue comes in from my GameManager class. On the console, the beginning section should print out "You are the room at (Column=0, Row=0), but it prints this instead:
Here is the code for my GameManager class:
internal class GameManager
{
private bool IsGameOver;
private Player Player;
private Updater Updater;
// Don't need to call Fountain or Coordinate since they're static
public GameManager()
{
IsGameOver = false;
Player = new();
Updater = new();
}
public void RunGame()
{
while (!IsGameOver)
{
Console.WriteLine("----------------------------------------------------------");
Updater.DisplayPlayerPosition(); // This is the main line that I'm having issues with as of right now. All other functions past this are another problem.
Updater.DisplayPlayerSenses();
string playerInput = Player.GetInput();
Updater.MovePlayer(playerInput);
IsGameOver = Updater.CheckForWin();
}
}
}
And just to make sure, here is the code from my updater class, with the specific method that I'm having issues with:
internal class Updater
{
// No fields
// Default constructor
// Gets the text to show the player his current position.
public void DisplayPlayerPosition() // This is the method that I'm having issues with.
{
Console.WriteLine($"You are in the room at (Column={Coordinate.PlayerColumn}, Row={Coordinate.PlayerRow})");
}
...
I'm fairly new to the static keyword so I believe that I may be missing smth. I personally believe that it's because the class itself hasn't been initialized (like I haven't called the constructor for the Coordinate class, and apparently you can't call a static constructor anyways), but that's just me. If I could get any help, I'd greatly appreciate it!
PlayerColumn() and PlayerRow() are methods, but you are accesing them in the WriteLine statement as if they are properties.
Update your WriteLine to:
Console.WriteLine($"You are in the room at (Column={Coordinate.PlayerColumn()}, Row={Coordinate.PlayerRow()})");

Constructor does not pass initial array values to the method

I would like an explanation what I'm doing wrong. I paste two block of codes; one is working another is not working. The first code works becasue the initial values are passed into the method "MyGreatMethod" I can see them:
public class Something
{
private int [] MyArray = new int [3];
public Something()
{
MyArray[0] = 100;
MyArray[1] = 200;
MyArray[2] = 300;
}
public void MyGreatMethod()
{
Console.WriteLine(MyArray[0] / 3);
Console.WriteLine(MyArray[1] / 3);
Console.WriteLine(MyArray[2] / 3);
}
}
but if I place values into "MyArray" this way(see below), the method "MyGreatMethod" gets NULLs from constructor, what I do wrong? Please help..
public class Something
{
private int [] MyArray = new int [3];
public Something()
{
int[] MyArray = {100,200,300};
}
public void MyGreatMethod()
{
Console.WriteLine(MyArray[0] / 3);
Console.WriteLine(MyArray[1] / 3);
Console.WriteLine(MyArray[2] / 3);
}
}
It is null because you haven't assigned the values to MyArray. Instead, you have created a new array and assigned it to a local variable with the same name.
You should remove the int[] from the constructor:
public class Something
{
private int [] MyArray = new int [3];
public Something()
{
MyArray = {100,200,300};
}
public void MyGreatMethod()
{
Console.WriteLine(MyArray[0] / 3);
Console.WriteLine(MyArray[1] / 3);
Console.WriteLine(MyArray[2] / 3);
}
}
You need to use new keyword when you want to set values for a specific array after the declaration:
public class Something
{
private int[] MyArray;
public Something()
{
MyArray = new int[3] { 100, 200, 300 };
}
public void MyGreatMethod()
{
Console.WriteLine(MyArray[0] / 3);
Console.WriteLine(MyArray[1] / 3);
Console.WriteLine(MyArray[2] / 3);
}
}

Assigning to a variable by reference?

Thanks to the kind folks who answered my previous question from a few days ago, I now know how to pass arguments by reference:
static void Main()
{
int i = 0;
Add(ref i, 100);
// now i == 100
}
static void Add(ref int arg, int increment)
{
arg += increment;
}
But is there a way for me not to just pass i by reference, but actually store its location in another variable? By that I mean use i like I did in my example; affecting the original instance, but in a way that's permanently linked and not leaving scope.
I vaguely know that I could use a pointer to determine the location in unsafe context but I was wondering if I could do this without any of that, or if it is just recommended to use the unsafe method.
If you are using C# 7 you can use ref local and ref return to store an updateable reference to any field.
In this example I change the private field _privateField from 0 to 100 from outside Foo, the class in which it is defined, by returning it as a ref int and updating it by reference.
class Foo
{
private int _privateField = 0;
public ref int GetReference()
{
return ref _privateField;
}
public override string ToString()
{
return _privateField.ToString();
}
}
public class Program
{
public static void Main()
{
var foo = new Foo();
var referenceToPrivateField = foo.GetReference();
referenceToPrivateField = 100;
Console.WriteLine(foo);
}
}
Prior to that, you'd have to store the value in a field contained in an object, and pass around a reference to the object instead.
In this example I change the value from 0 to 100 from outside Foo, even though it is stored (indirectly) in a field that is private inside the Foo instance.
class ValueTypeReference<T> where T : struct
{
public T Value { get; set; }
}
class Foo
{
private ValueTypeReference<int> _privateField = new ValueTypeReference<int>{ Value = 0 };
public ValueTypeReference<int> GetReference()
{
return _privateField;
}
public override string ToString()
{
return _privateField.Value.ToString();
}
}
public class Program
{
public static void Main()
{
var foo = new Foo();
var referenceToPrivateField = foo.GetReference();
referenceToPrivateField.Value = 100;
Console.WriteLine(foo);
}
}
Output:
100
Well, if I udnerstood you correctly, you want the variable to have global scope, which can be achieved by putting variable as class field/property:
class Program
{
private static int _i;
static void Main()
{
_i = 0;
Add(100);
// now _i == 100
}
static void Add(int increment)
{
_i += 100;
}
}

Loop not running when its method to run it is called

If I call the default constructor "Creature" in main and then try to call the method "Generate Creator" the loop never runs. If I did a normal for loop it throws out of bounds errors even knowing the default constructor sets the length of the array. It is probably a dumb error I am not seeing. (this isnt all of the code)
class Creature
{
static int geneLength;
byte[] Chromosome = new byte[geneLength];
int fitness;
string geneString;
Random rn = new Random();
public Creature()
{
geneLength = 36;
fitness = 0;
}
public void GenerateCreature()
{
foreach(byte g in Chromosome)
{
Chromosome[g] = (byte)rn.Next(0, 2);
geneString += Chromosome[g].ToString();
}
}
}
Main:
namespace Creature_Generator
{
class Program
{
static void Main(string[] args)
{
Creature c = new Creature();
c.GenerateCreature();
Console.WriteLine(c.getGeneString);
}
}
}
foreach(byte g in Chromosome)
{
Chromosome[g] = (byte)rn.Next(0, 2); // 'g' is not an index
geneString += Chromosome[g].ToString(); // 'g' is not an index
}
while you are using foreach (byte g in Chromosome), I believe it is not a proper way to use code like Chromosome[g] which g is suppose a value not an index
try
StringBuilder geneString = new StringBuilder();
public Creature()
{
geneLength = 36;
this.Chromosome = new byte[geneLength];
fitness = 0;
}
for (int i = 0; i < this.Chromosome.Length; i++)
{
byte g = this.Chromosome[i]; // this line is useless
this.Chromosome[i] = (byte)rn.Next(0, 2);
geneString.Append(this.Chromosome[i].ToString());
}
Plus, if you are hard-coding geneLength = 36 in the constructor, consider use public int geneString { get; private set;} instead of static int geneLength; or
static int _geneLength = 36;
public int geneLength { get; private set; }
public Creature() { this.geneLength = _geneLength; }
public Creature(int geneLength) { this.geneLength = geneLength; }
Edit 1 -
According to #moreON advice, string geneString is modified from class string to StringBuilder, read more on https://msdn.microsoft.com/en-us/library/system.text.stringbuilder(v=vs.110).aspx
Other than your issue attempting to use the results of foreach to index an array, as others have mentioned, you're also ignoring the order in which initialisers and constructors are executed.
If we ignore inheritance (because you have none that is interesting here). Initializers are run before constructors.
This means that you are creating the array Chromosome before assigning 36 to geneLength. This means that geneLength was still default(int), which is 0, so you created an array with length 0.
For more on c# constructors see Jon Skeet's excellent page: http://jonskeet.uk/csharp/constructors.html
geneLength should probably also not be static, but that's a different discussion.
If you want geneLength to be a static field then you need to initialize it with a static constructor. Otherwise the value of geneLength is still 0 at the moment you instantiate the class.
Write your code like this instead:
class Creature
{
static int geneLength;
byte[] Chromosome = new byte[geneLength];
int fitness;
string geneString;
Random rn = new Random();
static Creature()
{
geneLength = 36;
}
public Creature()
{
fitness = 0;
}
public void GenerateCreature()
{
foreach (byte g in Chromosome)
{
Chromosome[g] = (byte)rn.Next(0, 2);
geneString += Chromosome[g].ToString();
}
}
}

member variable not an option

I have many constants I need to move around in one of my classes but I'm not allowed to use member variables. What are some options?
Here's my initial try:
private void MyConstants(out int textSize, out int paddingValue, out int borderType, ...)
{
//Set them here
}
private Method1()
{
int textSize = 0;
int paddingValue = 0;
int borderValue = 0;
....
MyConstants(out textSize, out paddingValue, out borderValue)
}
private Method2()
{
int textSize = 0;
int paddingValue = 0;
int borderValue = 0;
....
MyConstants(out textSize, out paddingValue, out borderValue)
}
//Many more methods...Just seems to repetitive.
Use Private Class or Struct.
private class Variables {
public int textSize;
public int paddingValue;
public int borderValue;
}
private Variables MyConstants{
get{ return new Variables(){textSize=1, paddingValue=2, borderValue=3};}
}
If you need to initialize in constructor try using readonly instead on const.
Edit 1:
You can create a class that holds a private Dictionary:like key and value.
put a "object LoadConstant(string)" method in it that will withdraw the data.
public static class ConstantManager {
private static Hashtable _consts = new Hashtable();
private static const keyName = "Name 1";
public static void ConstantManager()
{
_consts[keyName] = ...;
}
public static Hashtable GetConstants()
{
var _copy = new Hashtable(_consts);
return _copy;
}
}
public OtherClass{
public void Method()
{
var consts = ConstantManager.GetConstants();
var a = consts[ConstantManager.keyName];
}
}

Categories

Resources