How to access second Dimension of Array [duplicate] - c#

This question already has answers here:
Two dimensional array slice in C#
(3 answers)
Closed 8 years ago.
Following situation:
I have a Array which got 2 dimension. No i want to access the second dimension. How can i achieve this goal?
Here my code to clarify my problem:
private static int[,] _Spielfeld = new int[_Hoehe, _Breite];
private static bool IstGewonnen(int spieler)
{
bool istGewonnen = false;
for (int zaehler = 0; zaehler < _Spielfeld.GetLength(0); zaehler++)
{
//Here i cant understand why compiler doesnt allow
//Want to give the second dimension on the Method
istGewonnen = ZeileSpalteAufGewinnPruefen(_Spielfeld[zaehler] ,spieler);
}
return istGewonnen;
}
//This method want to become an Array
private static bool ZeileSpalteAufGewinnPruefen(int[] zeileSpalte, int spieler)
{
//Some further code
}
The compiler is saying: "Argument from type int[,] is not assignable to argument of type int[]. In Java it is working as i expected. Thanks in advance.

Define your array as a jagged array (array of arrays):
private static int[][] _Spielfeld = new int[10][];
Then loop through the first dimension and initialize.
for (int i = 0; i < _Spielfeld.Length; i++)
{
_Spielfeld[i] = new int[20];
}
Then the rest of your code will compile OK.

C# allows two different offers two flavors of multidimensional arrays which, although they look quite similar, handle quite differently in practice.
What you have there is a true multidimensional array, from which you cannot automatically extract a slice. That would be possible (as in Java) if you had a jagged array instead.
If the choice of having a multidimensional array is deliberate and mandatory then you will have to extract slices manually; for example see this question.
If the choice between jagged and multidimensional is open then you can also consider switching to a jagged array and getting the option of slicing for free.

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

Casting non-0-based array created by c# Array.CreateInstance to collection T [duplicate]

This question already has an answer here:
What does System.Double[*] mean
(1 answer)
Closed 5 years ago.
I'm trying to convert vb6 code to c# code.
My vb6 source code contains arrays of the most varied types and after conversion by Vs2005 tools these arrays have become 0-based array, but I need to reconvert to non-0-based array.So for example I try to use Array.CreateInstance with explicit cast to T[] for a generic use:
public void ResizeArrayBaseN<T>(ref T[] original, int firstLower, int firstCount)
{
try
{
int[] myBoundsArray = new int[1] {firstLower };
int[] myLengthsArray = new int[1] {firstCount - firstLower + 1 };
original = (T[])Array.CreateInstance(typeof(T), myLengthsArray, myBoundsArray);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
But I'm catching cast from T[*] to T[] error.
Can someone help me,please ?
Thanks in advance
A T[] is a vector array - a zero-based one-dimensional array. You cannot use T[] to represent an array with a non-zero base, because: it isn't a vector. This is what the * in T[*] means. I suspect it can only be referenced as an Array - making it quite inconvenient to use.

Copy array of one type to array of different type [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I was wondering if it's possible to use some sort of Array.Copy method in C# to copy elements of one array to and array of same size but different type.
I get a struct from a native c++ library that contains a pointer to Integer and a size element. These integer values represent enum Values from enum Foo.
At the moment I'm using a for loop. Is there a better/safer approach?
Thanks!
Using Array.Copy throws an ArrayTypeMismatchException as shown below:
using System;
public class Program
{
public enum Foo
{
FOO_1,
FOO_2
}
public static void Main(string[] args)
{
int nCount = 1;
Foo[] fooArr = new Foo[nCount];
Int32[] RawData = new Int32[nCount];
RawData[0] = 100;
Array.Copy(RawData, fooArr, nCount);
}
}
You could do it with LINQ:
fooArr = RawData.Select(r => (Foo)r).ToArray();
For some reason, neither Array.Copy nor Buffer.BlockCopy is happy to copy from an int[] to a Foo[], although Array.Copy can go in the other direction perfectly happily.
It looks to me like your options are:
The kind of copy you showed in your original post, although I'd write it as:
for (int i = 0; i < RawData.Length; i++)
{
fooArr[i] = RawData[i];
}
.. that way you don't have a redundant variable outside the scope of the loop
A LINQ-based approach as suggested by Romano Zumbé, although in that case you shouldn't create the array beforehand as well
A LINQ-like-but-not-LINQ approach using Array.ConvertAll:
var fooArr = Array.ConvertAll(RawData, x => (Foo) x);
... this is more efficient than the LINQ approach as it can create an array of the correct size to start with.
If you don't need the execution-time type to actually be Foo[], you can just cast without any copying... because the CLR is happy to treat an int[] as a Foo[]:
Foo[] fooArr = (Foo[]) (object) RawData;
At that point, you have a single array object, which you're viewing as either an int[] (via RawData) or a Foo[] (via fooArr). Changes via either variable will be visible in the other variable. This is clearly very efficient, but could lead to problems elsewhere depending on how you use fooArr. If you just use it in foreach loops or via regular index accesses, it would be fine.

What is the difference between string[][] and string[,] in C# [duplicate]

This question already has answers here:
Differences between a multidimensional array "[,]" and an array of arrays "[][]" in C#?
(12 answers)
Closed 7 years ago.
The syntax is slightly different but what is the difference between them.
public static string[][] str1 = { new string[] { Total, "N2" }};
public static string[,] str2 = { { Total, "N2" } };
What are the guidelines for the use of each?
Have a look here:
https://msdn.microsoft.com/en-us/library/2s05feca.aspx
Basically, the difference is how the memory is allocated.
[,] notation will allocate all of the needed memory in one block, while [][] notation will allocate an array of pointers to arrays, where each array is allocated separately and not necessarily next to the others
In the examples you quoted:
public static string[][] str1 = { new string[] { Total, "N2" }};
public static string[,] str2 = { { Total, "N2" } };
The first one is an array of arrays (Jagged Array). Each entry can point to an array of string.
The second one is a normal 2 dimensional array (Multi Dimensional Array).
In a nutshell , [,] is a 2d array allocated all at once, while [][] is an array of arrays thus memory allocation is gradual- the initialization syntax (as you pointed out) is different also.
One more important difference is that in a [][] type you can define each 'row' of a different size. which you can't do in [,] which is in a way a C# representation of a Matrix.

In c#, if I have already declared an array of length n, how can I add another element on to it, making it of length (n+1)? [duplicate]

This question already has answers here:
Most efficient way to append arrays in C#?
(11 answers)
Closed 8 years ago.
Background on the program: the heart of the program needs to track all other Forms or other elements of the program. To do this, I am using a Form array
What I am wanting to do is take my initially defined array containing 1 element, and increase the length of the array to add a new element whenever a new Form is launched.The trouble I've run into is that I can't find out how to do this without using a second array to store the old array, re-declaring the original array with array.length += 1, looping through to re-add the original content from the second array, then adding the new element. It's heavy and inconvenient since I need to use similar processes elsewhere.
The code I have, which works but is ugly, is this:
public class PCB
{
Form[] Runners;
public PCB()
{
Runners = new Form[1];
Runners[0] = new GUI;
.
.
.
.
.
void NewForm(Form app)
{
Form[] TEMP = Runners; //Create my new array equal to the first
Runners = new Form[Runners.Length + 1]; //re-create the old array, with an additional element
for (int k = 0; k < TEMP.Length; k++)
{
//add the original elements back to the original array
Runners[k] = TEMP[k];
}
Runners[TEMP.Length] = App; //add the final element to the array
I hate having to use the loop-structure, as I feel that it can be done cleaner. what I'm looking for is a function similar to the ListBox.Items.Add([[ITEM]]), but for an array.
Does such a function exist, or do I need to continue with my ugly loops?
Use a list instead:
List<Form> Runners = new List<Form>();
...
Runners.Add(app);
If you for some odd reason absolutely must use an array, then Array.Resize is what you're looking for, but a list is much better.
I believe what you're looking for is a List. A List already does this for you under the hood in .NET. You can do this:
List<Form> Runners;
Runners = new List<Form>();
Now when you add to the list you can do:
Runners.Add(new MyForm());
When you want to remove from the list you can do:
Runners.Remove(MyForm);
Just use a List<Form> list instead of arrays, which can be accessed just like an array and you can dynamically add other elements (list.Add(new Form(...))).
It is much more performant than an array and it has other features that can simplify your coding.
One way is to use Array.Resize
P.S. !!! be sure that the references to your array won't be changed.
Here is an example:
using System;
class aaa
{
static void Main()
{
string[] array = new string[10];
Array.Resize(ref array, 20);
}
}

Categories