Declare an array of queues [duplicate] - c#

This question already has answers here:
All possible array initialization syntaxes
(19 answers)
Closed 5 years ago.
What is the language grammatical problem in my code?
I want to declare an array of queues. Is this the right way to declare and use them?
public static void Main(string[] args)
{
Queue<int>[] downBoolArray = new Queue<int>[8]();
downBoolArray[0].Enqueue(1);
}

Your first problem is a syntax error: new Queue<int>[8]() should be new Queue<int>[8].
Once declared with the correct syntax, when you attempt to use an element of the array (downBoolArray[0].Enqueue(1)) you will encounter a NullReferenceException because array elements initialise to their default values which in the case of a reference type is null.
You could instead initialise your array with non-null seed values using a single line of LINQ:
Queue<int>[] downBoolArray = Enumerable.Range(1,8).Select(i => new Queue<int>()).ToArray();
The arguments to Range specify that we need 8 'entries' in our sequence; the Select statement creates a new Queue<int> for each item; and the ToArray call outputs our sequence as an array.

You need to initialize each element in your array
void Main()
{
Queue<int>[] downBoolArray =new Queue<int>[10];
for (int i = 0; i < downBoolArray.Length; i++)
downBoolArray[i] = new Queue<int>();
downBoolArray[0].Enqueue(1);
}

You've created an array of null values.
What you want is something like this:
public static void Main(string[] args) {
var queues = new Queue<int>[8];
// Possibly some other stuff
// Initialise all values
for (var i = 0; i < queues.Length; i++) {
// Accounting for maybe already sporadically initialising values
queues[i] = (queues[i]) ?? new Queue<int>();
}
// Do whatever
}

Related

How to change an array in a function without changing the original array? [duplicate]

This question already has answers here:
Copy Arrays to Array
(7 answers)
Closed 1 year ago.
In C# and many other languages, if you pass an array to a function it passes the pointer/reference which means you can change the value of an array from inside a function.
From Microsoft:
Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.
I have a special case where I need to access and change an array's contents from a function but I do not want to change the original array. I thought this would be quite simple. I could set a new array equal to the old array and change the new array. This acts the same, however, because the new array is just a pointer to the old one.
static void AddToArray(string[] array) {
var newArray = array;
newArray[2] = "y";
}
static void Main(string[] args) {
string[] array = new string[5];
array[0] = "h";
array[1] = "e";
AddToArray(array);
}
If you print the contents of array at each step:
"he"
"hey" (inside function)
"hey" (after function call)
I've done a lot of research online but somehow haven't found many other people who needed help with this. Advice is greatly appreciated!
You are not creating your array using "new" Keyword inside function. Change below line -
var newArray = array;
To
var newArray = new string[args.Length];
and after creating this as a new array, you can copy the values from args (passed) array

Instantiation of every array element(class) - C# [duplicate]

Given a class:
class clsPerson { public int x, y; }
Is there some way to create an array of these classes with each element initialized to a (default) constructed instance, without doing it manually in a for loop like:
clsPerson[] objArr = new clsPerson[1000];
for (int i = 0; i < 1000; ++i)
objArr[i] = new clsPerson();
Can I shorten the declaration and instantiation of an array of N objects?
The constructor must be run for every item in the array in this scenario. Whether or not you use a loop, collection initializers or a helper method every element in the array must be visited.
If you're just looking for a handy syntax though you could use the following
public static T[] CreateArray<T>(int count) where T : new() {
var array = new T[count];
for (var i = 0; i < count; i++) {
array[i] = new T();
}
return array;
}
clsPerson[] objArary = CreateArray<clsPerson>(1000);
You must invoke the constructor for each item. There is no way to allocate an array and invoke your class constructors on the items without constructing each item.
You could shorten it (a tiny bit) from a loop using:
clsPerson[] objArr = Enumerable.Range(0, 1000).Select(i => new clsPerson()).ToArray();
Personally, I'd still allocate the array and loop through it (and/or move it into a helper routine), though, as it's very clear and still fairly simple:
clsPerson[] objArr = new clsPerson[1000];
for (int i=0;i<1000;++i)
clsPerson[i] = new clsPerson();
If it would make sense to do so, you could change class clsPerson to struct Person. structs always have a default value.

C# passing jagged array in class constructor [duplicate]

This question already has answers here:
Passing Arrays by Value and by Reference
(4 answers)
Closed 5 years ago.
I have a jagged array that I pass to object constructor but whenever I edit the array that I passed as parameter, the array inside the instance of the object also gets edited for some reason.
bool[][] clickedArray = new bool[7][];
clickedArray[0] = new bool[3];
clickedArray[1] = new bool[3];
clickedArray[2] = new bool[3];
clickedArray[3] = new bool[2];
clickedArray[4] = new bool[3];
clickedArray[5] = new bool[3];
clickedArray[6] = new bool[4];
I read some ints from a file and set the bools to true or false depending on the ints. By default, all elements of the jagged array are set to false:
for (int i = 0; i < clickedArray.Length; i++) // i < 7
{
for (int j = 0; j < clickedArray[i].Length; j++)
{
clickedArray[i][j] = false;
}
}
I also have a List of objects. I call the constructor by adding new instance of the object to the list: buildsList.Add(new Builds(tokens[0], clickedArray));
Here is the constructor:
public Builds(string buildName, bool[][] jagged)
{
this.buildName = buildName;
jaggedArray = jagged;
}
I don't know why but when I, for example, reset the array and then call a function such as:
int selection = comboBox1.SelectedIndex;
clickedArray = buildsList[selection].getJaggedArray();
it turns out that the jagged array from the object inside the list also had it's values reset.
Arrays in .NET are object on the heap, so you have a reference. That reference is passed by value, meaning that changes to the contents of the array are reflected anywhere.
So: jaggedArray = jagged;
they have the same reference pointer to the same address in the memory.
Use Array.Copy method to avoid that issue in order to copy elements fr
om the source array to the destination. Check how to use Array.Copy Method.

How can I append values in a C# array? [duplicate]

This question already has answers here:
Adding values to a C# array
(26 answers)
Add new item in existing array in c#.net
(20 answers)
Closed 5 years ago.
I need to add values to my array one integer value at a time, via user input.
I don't know how to ask it more clearly, but my goal is to define an integer array in Main(), then pass it to Interactive() where a user is supposed to enter 20 different ints and the program should add them to the array.
It would be tedious to continue defining new arguments for each object (like this):
int One = ArrayOne[0]
int Two = ArrayOne[1]
int Three = ArrayOne[2]
because I am filling 20 array objects, surely there is an easier way?
Can someone help?
Here is the code I am working with:
class Program
{
static void Main(string[] args)
{
int[] intArray = new int[20];
}
public static int[] Interactive(int[] args)
{
int[] ArrayOne = new int[20];
Write("\n Write an integer >>");
ArrayOne[0] = Convert.ToInt32(ReadLine());
foreach (int x in ArrayOne)
{
if (x != ArrayOne[0])
Write("\n Write another integer");
ArrayOne[x] = Convert.ToInt32(ReadLine());
WriteLine("\n {0}", ArrayOne[x]);
}
ReadLine();
return ArrayOne;
}
}
Try using a List. Unlike arrays their size can be dynamically changed.
using System.Collections.Generic;
public class Example
{
public static void Main()
{
List<int> numbers = new List<int>();
numbers.add(1);
numbers.add(2);
}
}
Are you looking for this?
int[] intArray = Interactive(values here);
public static int[] Interactive(int[] args)
{
//TODO:
}

List Collection object as Method Parameter

Can anyone explain how the memory allocation is done while invoking a method having list collection as parameter. Since the code snippet below though apparently seems to result same but it is not resulting same.
So I would like to know the difference in both the method call in terms of memory allocation.
using System;
using System.Collections.Generic;
namespace ListSample
{
class ListSampleClass
{
static void Main(string[] args)
{
List<int> i = new List<int>();
i.Add(10);
i.Add(15);
SampleMethod1(i);
Console.WriteLine("Result of SampleMethod1:"+i[0]);
SampleMethod2(i);
Console.WriteLine("Result of SampleMethod2:" + i[0]);
Console.ReadKey();
}
public static void SampleMethod1(List<int> i)
{
List<int> j = new List<int>();
j.Insert(0,20);
i = j;
}
public static void SampleMethod2(List<int> i)
{
List<int> j = new List<int>();
j = i;
j.Insert(0, 20);
}
}
}
Unless you specify ref or out, parameters are passed by value. For reference types, that means a reference to the object (the List<int> in this case) is passed by value.
"Pass by value" means that the argument (the expression in the calling statement) is evaluated, and then the resulting value is copied into the parameter (the variable listed in the method signature). Any further changes to the parameter, in terms of assigning it a new value, are not seen by the caller. (But keep reading...)
That means that in your first method call:
public static void SampleMethod1(List<int> i)
{
List<int> j = new List<int>();
j.Insert(0,20);
i = j;
}
you're creating a new list, inserting a value into it, and then copying the reference to that new list to i - but that has no effect at all. The parameter is effectively just another local variable - a change to the value of the variable itself doesn't affect the caller.
Now compare that with your second method:
public static void SampleMethod2(List<int> i)
{
List<int> j = new List<int>();
j = i;
j.Insert(0, 20);
}
This creates a new list and then immediately ignores it, instead assigning the reference to the list passed in (as i) to j. It then inserts a value into the list. The net result of this method is that a value is inserted into the list. It's equivalent to:
public static void SampleMethod2(List<int> i)
{
i.Insert(0, 20);
}
Note that this is not changing the value of the parameter. It's making a change to the object that the value of the parameter refers to. This is a crucial difference to understand.
I have an article on parameter passing and another one on reference and value types which may help you understand this more.

Categories