I created a small piece of code in order to test part of my project. It is working however I have some questions...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace testtodel
{
class Program
{
private class BucketItems
{
private List<Item> ItemList;
private Item item;
public BucketItems()
{
//item = new Item();
ItemList = new List<Item>();
}
public void AddBucketItem(int _Start, int _End)
{
item = new Item();
item.SetItem(_Start, _End);
ItemList.Add(item);
}
public void PrintItemList()
{
for (int i = 0; i < ItemList.Count(); i++)
{
Console.WriteLine("Item: " + i.ToString() + " S: " + ItemList[i].Start.ToString() + " E: " + ItemList[i].End.ToString() + " D: " + ItemList[i].Range.ToString());
}
}
}
private class Item
{
public int Range { get; set; }
public int Start { get; set; }
public int End { get; set; }
public void SetItem(int _Start, int _End)
{
Start = _Start;
End = _End;
Range = _End - _Start;
}
}
static void Main(string[] args)
{
BucketItems bucketItems = new BucketItems();
bucketItems.AddBucketItem(0, 100);
bucketItems.AddBucketItem(200, 300);
bucketItems.AddBucketItem(700, 1000);
bucketItems.PrintItemList();
Console.ReadLine();
}
}
}
The thing which I do not fully understand is related to line
item = new Item();
As you can see in code there are 2 lines like that, one commented and one uncommented.
Part_1:
When code is executed as it is now, it will create a new instance of 'Item' class each time when 'AddBucketItem' method is called, then 'Item.SetItem' will set 'Start', 'End', 'Range' within 'item' variable and this will be added to 'ItemList'.
Part_2:
When I will comment exisiting 'item = new Item();' line and uncomment other one then I will expect the following. When new instance of BucketItem class is created it will also create a new instance of 'Item' as this is defined in the 'BucketItem' constructor. Then, when 'AddBucketItem' method is called, an 'item' varaible will be set by 'item.SetItem' and then, added to ItemList.
This is ok for the first iteration. However if I will call 'AddBucketItem' method again, with new 'Start' and 'End' parameters, this will also change already added ItemList[0].
Questions:
Why each call in Part_2 is changing also all elements which were already added to ItemList? The only explanation is that all elements from list are storing a reference to 'item' variable and when this variable is changed by changing (Start, End, Duriation) it wil also change all ItemList. But I don't know if this is correct explanation and if it is I don't know why it is behaving like this. Hovever I am assuming that answer is different becasue the following example will fill the list as expected even when I am doing exactly the same thing as in 'Part2'.. I have variable, I am changing value of variable, I am adding this variable to list.
int new_val;
List<int> _lst = new List<int>();
for (int i = 0; i < 10; i++)
{
new_val = i;
_lst.Add(new_val);
}
for (int i = 0; i < _lst.Count(); i++)
{ Console.WriteLine("ListIdx: " + i.ToString() + " Value: " + _lst[i].ToString()); }
Can someone please put some more light on my issue?
In your example, new_val is int which is value type.
At the same time, in the first code snippet, Item is a class, which is reference type.
If you use approach described in Part_2, then you actually operate with one object. So, your ItemList contains N items, which are all the same object.
In Part_1, every time you call AddBucketItem, you create a new object and append it to your list.
In Part_2, everytime you call AddBucketItem, you modify the single original Item object.
You may want to read some information on value types and reference types on MSDN:
https://msdn.microsoft.com/en-us/library/4d43ts61(v=vs.90).aspx
You need to understand that in C#, objects are passed by reference and primitive types are passed by value.
Therefore, your understanding for the AddBucketItem example is correct. The Item object is only created once in the BucketItems constructor. When you call AddBucketItem(), you are modifying the original instance and adding its reference into the list. So in the end, you have a list with individual item all pointing to the same object instance.
For the 2nd example you provide, it behaves differently because for int type, which is a primitive data type, the value passed into the Add() function is a copy of the integer, not a reference.
Related
I am trying to add a few different members to a list, but when the list is added to it contains copies of only the last member added:
private PotentialSolution tryFirstTrack(PotentialSolution ps, List<PotentialSolution> possibleTracks)
{
for (Track trytrack = Track.Empty + 1; trytrack < Track.MaxVal; trytrack++)
{
if (validMove(ps.nextSide, trytrack))
{
ps.SetCell(trytrack);
possibleTracks.Add(ps);
}
}
return tryNextTrack(ps, possibleTracks);
}
The PotentialSolution class looks like this:
public class PotentialSolution
{
public Track[,] board;
public Side nextSide;
public int h;
public int w;
static int cellsPerSide;
static bool testing;
static int minTracks;
.....
public void SetCell(Track t)
{
board[h, w] = t;
}
}
So we are trying to make several copies of the board which only differ by which 'track' is placed in the current cell.
If I have a breakpoint at possibleTracks.Add(ps) then I can see by inspecting ps that the required cell contents is changing each time, as required.
But when the code reaches the next line (or the return statement), the cell content is the same in each member of the list (it's the last one that was added).
What I am doing wrong here? I have tried using an ArrayList and also a basic array instead, but get the same result. It's acting as though the board member is decared as static, but it's not.
[edit]
In response to those who suggested making copies of ps, you are correct and I had tried this before - but only tried single-stepping after the change and didn't run the full program (this method is used hundreds of times). When running the full program, making copies of ps certainly makes a difference to the result (although it's still not correct). The problem now, and why I didn't stick with using the copies, is that an added test still shows the list to contain the same versions of ps, even though the debugger has shown 2 or 3 different tracks being deployed:
private PotentialSolution tryFirstTrack(PotentialSolution ps, List<PotentialSolution> possibleTracks)
{
for (Track trytrack = Track.Empty + 1; trytrack < Track.MaxVal; trytrack++)
{
if (validMove(ps.nextSide, trytrack))
{
PotentialSolution newps = new PotentialSolution(ps);
newps.SetCell(trytrack);
possibleTracks.Add(newps);
}
}
// temporary test, can be removed
if (possibleTracks.Count >= 2)
{
PotentialSolution ps1 = new PotentialSolution(possibleTracks.First());
PotentialSolution ps2 = new PotentialSolution(possibleTracks.Last());
if (ps1.GetCell() != ps2.GetCell())
{
// should always get here but never does
int foo = 1;
}
}
return tryNextTrack(ps, possibleTracks);
}
By the way, Track and nextSide are just enum integers, they will be 0-6, and the list will contain 0,1,2,or 3 members, never more.
You are adding references to the same object: ps in possibleTracks.Add(ps)
You could add a constructor to PotentialSolution duplicating the class:
public class PotentialSolution
{
public Track[,] board;
public Side nextSide;
public int h;
public int w;
static int cellsPerSide;
static bool testing;
static int minTracks;
//.....
public PotentialSolution()
{
}
public PotentialSolution(PotentialSolution ps)
{
board = ps.board;
nextSide = ps.nextSide;
h = ps.h;
w = ps.w;
}
//.....
Then use:
private PotentialSolution tryFirstTrack(PotentialSolution ps, List<PotentialSolution> possibleTracks)
{
for (Track trytrack = Track.Empty + 1; trytrack < Track.MaxVal; trytrack++)
{
if (validMove(ps.nextSide, trytrack))
{
ps.SetCell(trytrack);
possibleTracks.Add(new PotentialSolution(ps)); // duplicate object
}
}
return tryNextTrack(ps, possibleTracks);
}
This creates a new instance of the class each time it is added to the list.
Consider giving the PotentialSolution type value semantics by making it a struct and implementing a Clone method, or a constructor that takes another PotentialSolution as an argument. Also, to clone a 2D array of value types, call Object.Clone() and cast the result to T[,].
When making a copy of your PotentialSolution, you'll need to make sure your clone your board array, because, in your case, each PotentialSolution keeps its own representation of the state of the board.
I feel like the critical part you're missing is how to shallow clone a 2D array, which in general, is:
T[,] copy = (T[,])original.Clone();
WARNING: Clone creates a shallow copy of the array. For value-types this copies the values of each element, so for your int-like "Track" type it does what you want, but for other readers who may be using reference-types (like classes) it does not clone each object referred to by each element of the array. The elements of the new array are just object references, and will still refer to the same objects referred to by the elements of the original array. See the documentation.
Full example below that changes the middle cell of a 3x3 board from A to B.
using System;
using System.Linq;
public enum Track { A, B, C }
public enum Side { X, Y, Z }
public struct PotentialSolution
{
public Track[,] board;
public Side nextSide;
public int h;
public int w;
public void SetCell(Track t)
{
board[h, w] = t;
}
public PotentialSolution(Track[,] board, Side nextSide, int h, int w)
{
this.board = (Track[,])board.Clone();
this.nextSide = nextSide;
this.h = h;
this.w = w;
}
public PotentialSolution Clone()
{
return new PotentialSolution(board, nextSide, h, w);
}
// This `ToString` is provided for illustration only
public override string ToString()
{
var range0 = board.GetLength(0);
var range1 = board.GetLength(1);
var b = board;
return string.Join(",",
Enumerable.Range(0, range0)
.Select(x => Enumerable.Range(0, range1)
.Select(y => b[x, y]))
.Select(z => "[" + string.Join(",", z) + "]"));
}
}
class Program
{
static void Main(string[] args)
{
Track[,] someBoard = new Track[3, 3];
PotentialSolution ps1 = new PotentialSolution(someBoard, Side.X, 1, 1);
ps1.SetCell(Track.A);
PotentialSolution ps2 = ps1.Clone();
ps2.SetCell(Track.B);
Console.WriteLine(ps1);
Console.WriteLine(ps2);
}
}
I'm filling in the blanks liberally, so please excuse any assumptions I have made that differ from your actual situation, because I have done so only to make this example self-contained. My ToString implementation and its usage of System.Linq is not necessary; it's purely for the purposes of displaying the 2D array in my example.
You always call SetCell on the same ps object you received as a parameter then add the same instance to the possibleTracks list. The result is: possibleTrack contains ps n times and because it is the same instance you used in each cycle it will have the last change you applied via SetCell call.
Not sure what you wanted to achieve but it looks you need a modified copy of ps in each cycle for adding to possibleTrack list. Making PotentialSolution a struct instead of class could be enough? Structs are copied in such a way but may hit your performance if PotentialSolution is big.
The board member will still generate the same problem, because despite ps will be copied but the board inside it will contain same Track references. The trick can be applied to Track too, but the performance issues may raise more.
Just implement a Clone on PotentialSolution to have fully detached instances of it, then call ````SetCell``` on cloned instance and add that instance to the list.
I want to add text to the class created in my code.
My problem is that it does not recognize the text and is not added.
In the created class, there are 3 sections, which are filled in 3 parts in order, but the main problem is that the text is not added in class c1.set1
This code is executed in Unity.
Also coded with Visual 2017.
I hope I have made the problem clear.
using System;
[Serializable]
public class c1
{
public string set1;
public string set2;
public string set3;
}
public class stringToArray : MonoBehaviour
{
public string[] S1;
public c1[] c1_item;
public int x;
// Start is called before the first frame update
void Start()
{
S1 = new string[20];// It works properly
while (x<10)
{
S1[x]= string.Format("ok "+x,x);
x++;
}
c1_item = new c1[20];
while (x < 10)
{
//S1[x] = string.Format("ok " + x, x); // It works properly
c1_item[x].set1 = string.Format("ok "+x , x); // It does not work properly
x++;
}
}
}
Does anyone know what to do?
Right, so your problem is that you haven't actually created the c1 objects to store your values, you've only created the c1_items array to hold the referencese to the objects.
void Start() {
// 'string' is (treated as) a value type, does not need to be initialised
S1 = new string[20];// It works properly
while (x < 10) {
S1[x] = string.Format("ok " + x, x);
x++;
}
x = 0; // reset x
// !! CAUSE: 'c1' is a reference type (class), it only holds references and not actual objects
c1_item = new c1[20];
while (x < 10) {
// !! FIX: MUST add the object first
if (c1_item[x] == null) c1_item[x] = new c1();
c1_item[x].set1 = string.Format("ok " + x, x); // It does not work properly
x++;
}
}
What can be tricky is that you've set c1_item as public, which means that Unity will instantiate and manage all the required objects within the array. The issue here is that you wipe that out and generate your own array (new c1[]), which means you also have to be the one to add the objects.
(Of note, if your c1 was a struct instead of a class this wouldn't have come up)
first of all using UnityEngine; might be helpful so don't always delete it
you need also using System.Collections; and using System.Collections.Generic; for the usage of lists and arrays.
I recommend that you initiate S1 before the start I mean in the awake method.
public int x = 0; // doesn't hurt to give it a value
you also need the x to be positive yes ? because it will be the index in a list of string so use range and test the x before working with it ,example :
[Range(0,20)]
public int x = 0;
Or
void Start()
{
if(x>=0){
//do code
}
}
Now why your code line doesn't work
c1_item[x].set1 = string.Format("ok "+x , x); // It does not work properly
I recommend using this
if(c1_item.Length >= x){
c1 newC1 = c1_item[x];
newC1.set1 = string.Format("ok "+x , x);}
I searched the heck out of it, and i can't solve it.
I have a program setup like this (it's in Unity and Visual Studio 2019 for C#):
Note that the CSV loading goes fine, when i debug the code i can see everything filled with corect data.
#region character class
public class _Character
{
public int Id { get; set; }
public int Variation { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
}
#endregion
//Tools.LoadCsv generates a string[,] from a csv file
//Tools.IntParse parses int's with a lot of format error checking
void Start()
{
#region load characters class
string[,] CharacterCSV = Tools.LoadCsv(#"Assets/GameDB/character.csv");
List<_Character> Character = new List<_Character>();
for (int i = 1; i < CharacterCSV.GetUpperBound(0); i++)
{
_Character temp = new _Character();
temp.Id = Tools.IntParse(CharacterCSV[i, 0]);
temp.Variation = Tools.IntParse(CharacterCSV[i, 1]);
temp.Name = CharacterCSV[i, 2];
temp.LastName = CharacterCSV[i, 3];
Character.Add(temp);
}
CharacterCSV = null;
#endregion
}
I barely understand objects, so i'm sorry if i am doing it wrong.
The questions i have are:
Why does the Object List generation Háve to be in Start ? I can't seem to do that in it's own class.
How can i get an object from the Character Object List, containing Id = 100 and Name = "John"
, and access it from another class or method.
I ussualy frankenstein the heck out of code and make it good enough for me, but now i wanted to make something nice and cant seem to get to the objects.
Thanks in advance!
//the major issue was declaring the object inside the class, when declared outside the class, the List Object was available to the outside world.
List<_Character> Character = new List<_Character>(); move to outside Start{}
I'm not editing the question to correct the code, because the question needs to stay clear.
//
Why does the Object List generation has to be in Start ? I can't seem to do that in it's own class.
How can i get an object from the Character Object List, containing Id = 100 and Name = "John" , and access it from another class or method.
If you want to retrieve a character from outside of the class, then, you have to declare the list outside of the Start function, otherwise, the list will be destroyed since it's a local variable of the function.
// Declare the list outside of the functions
private List<_Character> characters;
void Start()
{
// Avoid using regions, they encourage you to make very long functions with multiple responsabilities, which is not advised
// Instead, create short and simple functions, and call them
LoadCharactersFromCSV();
}
void LoadCharactersFromCSV()
{
string[,] CharacterCSV = Tools.LoadCsv(#"Assets/GameDB/character.csv");
// If you can, indicate the approximate numbers of elements
// It's not mandatory, but it improves a little bit the performances
characters = new List<_Character>( CharacterCSV.GetUpperBound(0) );
// I believe `i` should start at 0 instead of 1
for (int i = 1; i < CharacterCSV.GetUpperBound(0); i++)
{
// I advise you to create a constructor
// instead of accessing the properties one by one
_Character temp = new _Character();
temp.Id = Tools.IntParse(CharacterCSV[i, 0]);
temp.Variation = Tools.IntParse(CharacterCSV[i, 1]);
temp.Name = CharacterCSV[i, 2];
temp.LastName = CharacterCSV[i, 3];
characters.Add(temp);
}
CharacterCSV = null;
}
// Using this function, you will be able to get a character from its id
public _Character GetCharacter( int id )
{
for (int 0 = 1; i < characters.Count; i++)
{
if( characters[i].Id == id )
return characters[i];
}
// Return null if no character with the given ID has been found
return null ;
}
Then, to call GetCharacter from another class:
public class ExampleMonoBehaviour : MonoBehaviour
{
// Replace `TheClassName` by the name of the class above, containing the `Start` function
// Drag & drop in the inspector the gameObject holding the previous class
public TheClassName CharactersManager;
// I use `Start` for the sake of the example
private void Start()
{
// According to your code, `_Character` is defined **inside** the other class
// so you have to use this syntax
// You can get rid of `TheClassName.` if you declare `_Character` outside of it
TheClassName._Character john = CharactersManager.GetCharacter( 100 );
}
}
I have a 'Movie' class in my C# code that has an int[] ratings = new int[10]; as a field. I would like to place numbers in this empty array from my main program.
For that, I would need a method, that could point to the actual free index of the array to put the integer there, but the other integer that would point to the free index would be reset to 0 everytime the method is called. Thus, my question is, that how can I place an integer in my method that is increased everytime the method was called.
This is the method in the class:
public void Rate(int rating)
{
int x = 0;
ratings[x] = rating;
}
This is how I call it in the main program
Movie asd = new Movie(blabla...);
Rate.asd(1);
Rate.asd(1);
Rate.asd(1);
So I called it 3 times, and I would want the 'x' integer in the class's method to increase.
Thanks in advance.
First of all, you have an error in the code you have posted.
As I suppose rather than:
Movie asd = new Movie(blabla...);
Rate.asd(1);
Rate.asd(1);
Rate.asd(1);
you want to paste here:
Movie asd = new Movie(blabla...);
asd.Rate(1);
asd.Rate(1);
asd.Rate(1);
As C# does not allow to use static method variables (like i.e. C++ does) you have two options:
first, make x value (from Rate method) a Movie's class variable, so Rate method will "remember" the next index,
second (and better) rather than intiger array - if possible use any kind of list or queue (which can manage indexing for you).
The problem is that local variables are discarded when exiting a method.
class SomeClass
{
private int x = 42;
public void DoSometing(int y)
{
int a = y + 5;
x += a * a;
// a stops to exist here
}
}
Solution is to store the variable in the containing class as well
class SomeOtherClass
{
private int x = 42;
private int a = 0;
public void DoSomething(int y)
{
a = y + 5;
x += a * a;
}
}
Now SomeOtherClass remembers the value of a. That's basically the point of member variables a.k.a. fields - to store the state of the object.
More appropriate for your problem:
class ClassWithAnArrayAndCount
{
private int[] values = new int[10];
private int taken = 0;
public void Add(int value)
{
if (taken == 10)
throw new ArgumentOutOfRangeException(); // sorry, no more space
values[taken++] = value;
}
public int Taken { get { return taken; } }
}
my problem is as follows:
Im building a console application which asks the user for the numbers of objects it should create and 4 variables that have to be assigned for every object.
The new objects name should contain a counting number starting from 1.
How would you solve this?
Im thinking about a class but im unsure about how to create the objects in runtime from userinput. Is a loop the best way to go?
What kind of class, struct, list, array .... would you recommend. The variables in the object are always the same type but i need to name them properly so I can effectivly write methods to perform operations on them in a later phase of the program.
Im just learning the language and I would be very thankful for a advice on how to approach my problem.
If I understand your problem correctly:
class MyClass
{
public int ObjectNumber { get; set; }
public string SomeVariable { get; set; }
public string AnotherVariable { get; set; }
}
// You should use keyboard input value for this
int objectsToCreate = 10;
// Create an array to hold all your objects
MyClass[] myObjects = new MyClass[objectsToCreate];
for (int i = 0; i < objectsToCreate; i++)
{
// Instantiate a new object, set it's number and
// some other properties
myObjects[i] = new MyClass()
{
ObjectNumber = i + 1,
SomeVariable = "SomeValue",
AnotherVariable = "AnotherValue"
};
}
This doesn't quite do what you described. Add in keyboard input and stuff :) Most of this code needs to be in some kind of Main method to actually run, etc.
In this case, I've chosen a class to hold your 4 variables. I have only implemented 3 though, and I've implemented them as properties, rather than fields. I'm not sure this is necessary for your assignment, but it is generally a good habit to not have publically accessible fields, and I don't want to be the one to teach you bad habits. See auto-implemented properties.
You mentioned a struct, which would be an option as well, depending on what you want to store in it. Generally though, a class would be a safer bet.
A loop would indeed be the way to go to initialize your objects. In this case, a for loop is most practical. It starts counting at 0, because we're putting the objects in an array, and array indexes in C# always start at 0. This means you have to use i + 1 to assign to the object number, or the objects would be numbered 0 - 9, just like their indexes in the array.
I'm initializing the objects using object initializer syntax, which is new in C# 3.0.
The old fashioned way would be to assign them one by one:
myObjects[i] = new MyClass();
myObjects[i].ObjectNumber = i + 1;
myObjects[i].SomeVariable = "SomeValue";
Alternatively, you could define a constructor for MyClass that takes 3 parameters.
One last thing: some people here posted answers which use a generic List (List<MyClass>) instead of an array. This will work fine, but in my example I chose to use the most basic form you could use. A List does not have a fixed size, unlike an array (notice how I initialized the array). Lists are great if you want to add more items later, or if you have no idea beforehand how many items you will need to store. However, in this case, we have the keyboard input, so we know exactly how many items we'll have. Thus: array. It will implicitly tell whoever is reading your code, that you do not intend to add more items later.
I hope this answered some questions, and raised some new ones. See just how deep the rabbit hole goes :P
Use a list or an array. List example:
int numberOfObjects = 3;
List<YourType> listOfObjects = new List<YourType>();
for(int i = 0 ; i < numberOfObjects ; i++ )
{
// Get input and create object ....
// Then add to your list
listOfObjects.Add(element);
}
Here, listOfObjects is a Generic list that can contain a variable number of objects of the type YourType. The list will automatically resize so it can hold the number of objects you add to it. Hope this helps.
If I understood what you are asking you could probably do something like this:
class Foo
{
private static int count;
public string name;
public Foo(...){
name = ++count + "";
}
}
I'm guessing what you're trying to do here, but this is a stab in the dark. The problem I'm having is dealing with the whole "the new objects name should contain a counting number starting from 1" thing. Anyway, here's my attempt:
public class UserInstantiatedClass
{
public int UserSetField1;
public int UserSetField2;
public int UserSetField3;
public int UserSetField4;
public string UserSpecifiedClassName;
}
public static class MyProgram
{
public static void Main(string [] args)
{
// gather user input, place into variables named
// numInstances, className, field1, field2, field3, field4
List<UserInstantiatedClass> instances = new List< UserInstantiatedClass>();
UserInstantiatedClass current = null;
for(int i=1; i<=numInstances; i++)
{
current = new UserInstantiatedClass();
current.UserSpecifiedClassName = className + i.ToString(); // adds the number 1, 2, 3, etc. to the class name specified
current.UserSetField1 = field1;
current.UserSetField2 = field2;
current.UserSetField3 = field3;
current.UserSetField4 = field4;
instances.Add(current);
}
// after this loop, the instances list contains the number of instances of the class UserInstantiatedClass specified by the numInstances variable.
}
}