Learning some basics.. I'm trying to copy elements of an array to another. Let's say I don't know the size of the array 'bar'. So, I create an empty array 'arr' to copy the elements to bar into. The code below doesn't work.
It works if I replace
string[] arr ={} to string[] arr ={"",""}
How to declare an empty array and what should I modify in my code to achieve my goal?
Thanks!
//code
string[] bar = {"test", "user"};
string[] arr = {};
//iterate from the first to the last element of array bar
for (int i =0;i<bar.Length-1;i++)
{
Console.WriteLine("copy");
//copy string from bar to arr
arr[i]= bar[i];
//display the copied content from new array
Console.WriteLine(arr[i]);
}
in C#, arrays are of a fixed size. So when you create your array with size 0, you can't change the number of items it will contain, without re-instantiating it.
If you want to use a collection you can actively add/remove from (as is very common), consider using a List<T>:
string[] bar = {"test", "user"};
List<string> list = new List<string>();
for (int i =0;i<bar.Length-1;i++)
{
list.Add(bar[i]);
Console.WriteLine(list[i]);
}
By string[] arr = {}; you're instantiating an empty array of ZERO length, thus you need to define it like string[] arr = string[bar.Length];.
UPD:
Your code worked with string[] arr = {"",""}, because in this case you defined an array of length 2 using a two empty strings, but that's a code smell.
Arrays are fixed in size, which is why things like Lists are preferred over them.
In the case where you change your array definition to: string[] arr ={"",""} you are defining an array with a size of 2, same as your original array. When you try to copy it, the compiler already has everything allocated and ready to go, so it knows where position 0 and position 1 are in the array arr.
In the example in your code, where you have the array defined by string[] arr = {}; you are giving it an empty array (array size 0). The compiler has an issue, because it cannot reference position 0 or position 1 on an array that is empty.
You can modify the line as:
string[] arr = new string[4];
or
List<string> arr = new List<string>();
If you're going to use arrays, you'll want to create the second array as the same size as the first.
string[] bar = {"test", "user"};
string[] arr = new string[bar.Length];
If you know ahead of time that your array will be two, then you can just create it to be size two. Otherwise you'll want to inspect the size of the array you're copying from. If you know that you'll be adding and/or removing items, you'll want to use a different collection.
Related
This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed last year.
Here's my code:
using System;
public class Program
{
private static string[] ar = new string[] {};
public static void Main()
{
ar[0] = "hello";
Console.WriteLine("Total array length: " + ar.Length);
}
}
It show the error below when I run the above code:
Run-time exception (line 10): Index was outside the bounds of the array.
I thought that's how to define a dynamic array in C# but I must be missed something here.
You create an empty array, that is an array with fixed length 0 and no entries.
Consider List<string> ar = new List<string>() instead.
Related thread: Dynamic array in C#
EDIT: It later turned out the asker could use a Dictionary<int, string>. For a Dictionary<,>, the set accessor of the indexer (by which I mean the syntax ar[0] = "hello") will either create a new key/value pair (0 → "hello"), or overwrite the value of an already existing key (0).
Declaring private static string[] ar = new string[] {} actually means that you have an array of string with size of 0, i.e., empty array. C# doesn't allow to resize an array so you should initialize the array size if the length is fixed and this the reason you are getting the error Index was outside the bounds of the array. you are trying to set a value to an index which is larger then the array length.
In case the length is not fixed and you want to be dynamic, I recommend using List. Lists use arrays to store the data so you get the speed benefit of arrays with the convenience of a LinkedList by being able to add and remove items without worrying about having to manually change its size.
List<string> myList = new List<string>();
myList.Add("hello");
myList.Add("Ola");
private static string[] ar = new string[] {};
The above will create an empty array of string (i.e. allowed length = 0) and hence the IndexOutOfBound exception.
When you are not certain of the size of your collection, use List.
For e.g.: -
List<string> ar= new List<string>();
ar.Add("hello");
ar.Add("Ola");
Just out of curiosity, coming from C background, I knew that Array cannot be resized.
However, while I see in C#, it's so easy to do like below
var arr = new int[] {1,2,4,6};
arr = new int[2];
Also, there is a method available
Array.Resize(ref arr, 10);
How is it possible?
Thanks!
These operations aren't resizing the array. They're creating a new array of a new size.
Note in the first example that you call new twice. So you're creating two arrays.
In the second example, the documentation explains the same:
This method allocates a new array with the specified size, copies elements from the old array to the new one, and then replaces the old array with the new one.
The source code for the Array class can be found here.
This is the relevant portion:
T[] larray = array;
if (larray == null) {
array = new T[newSize];
return;
}
if (larray.Length != newSize) {
T[] newArray = new T[newSize];
Array.Copy(larray, 0, newArray, 0, larray.Length > newSize? newSize : larray.Length);
array = newArray;
}
As you can see, it allocates a new array and then copies whatever it can from the existing array into the new array.
Arrays cannot be resized in C#.
Your first example assigns a new array to the variable arr, it doesn't resize the existing array.
Also Array.Resize is a misnomer: it actually creates a new array and copies the values.
The clue to that is with the ref keyword, which indicates that Array.Resize will be reassigning to arr.
Each of those examples actually creates a brand new array, copies the items one by one from the old to the new, and updates the reference.
If you have a collection where the size will change over time, you're almost always better off using a generic List<T>.
I initiated an empty array - line.
string[] line = new string[] { };
I want to store every line that would be outputed in a cmd processing with the while loop below. This seems to work easily if I store the values in a string variable.
As shown below:
while (!proc.StandardOutput.EndOfStream)
{
line = proc.StandardOutput.ReadLine();
}
However, I'm not sure how to store the values as separate elements in the array. I've tried:
while (!proc.StandardOutput.EndOfStream)
{
for(a in line)
{
a = proc.StandardOutput.ReadLine();
}
}
But its not working.
This is probably a very basic question. But I'm still learning C#.
There are few solutions. One would be to use List<string> instead of string[]:
List<string> line = new List<string>();
And than add lines next way:
while (!proc.StandardOutput.EndOfStream)
{
line.Add(proc.StandardOutput.ReadLine());
}
An array works on the basis of indexing. So if you want to use an array you need to specify how long it has to be or in other words how many items it can contain:
// this array can store 100 items
string[] line = new string[100];
To access a certain position you need to use the [ ] operator and to move forward in the array you need an indexing variable of type int that you can increment each iteration
int indexer = 0;
while (!proc.StandardOutput.EndOfStream)
{
line[indexer] = proc.StandardOutput.ReadLine();
indexer ++; // increment
}
This way you need to know in advance how many items you want to deposit in your array.
Another way would be to use a flexible collection like List which can dynamically grow. Sidenote: The indexing works with the same [ ] operator, but the adding of items works via the Add method
If you want to know more have look at this overview of possible collection types
This question already has answers here:
Remove element of a regular array
(15 answers)
Closed 9 years ago.
string[] columns
I want to delete the item on an index specified by a variable of type int.
How do I do this ?
I tried
columns.RemoveAt(MY_INT_HERE);
But apparently this does not works.
Array is immutable class, you can't change it, all you can do is to re-create it:
List<String> list = columns.ToList(); // <- to List which is mutable
list.RemoveAt(MY_INT_HERE); // <- remove
string[] columns = list.ToArray(); // <- back to array
May be the best solution is to redesign your code: change immutable array into List<String>:
List<String> columns = ...
columns.RemoveAt(MY_INT_HERE);
If you don't want to use linq you can use this function :
public string[] RemoveAt(string[] stringArray, int index)
{
if (index < 0 || index >= stringArray.Length)
return stringArray;
var newArray = new string[stringArray.Length - 1];
int j = 0;
for (int i = 0; i < stringArray.Length; i++)
{
if(i == index)continue;
newArray[j] = stringArray[i];
j++;
}
return newArray;
}
You use it like that : columns = RemoveAt(columns, MY_INT_HERE)
You can also make it to an extension method.
You cannot delete items in an array, because the length of a C# array is fixed at the time when it is created, and cannot be changed after that.
You can null out the corresponding element to get rid of the string, or use LINQ to produce a new array, like this:
columns = columns.Take(MY_INT_HERE-1).Concat(columns.Skip(MY_INT_HERE)).ToArray();
You need to add using System.Linq at the top of your C# file in order for this to compile.
However, using a List<string> would be a better solution:
List<string> columns;
columns.RemoveAt(MY_INT_HERE);
Try one of the following (depending on what you need):
columns[MY_INT_HERE] = null;
columns[MY_INT_HERE] = string.Empty;
...otherwise you'll just have to create a new array which has a length of 1 less than your current array, and copy the values over.
If you want something more flexible, you might use a something like a List<string>, where you can use RemoveAt()
Arrays are faster for the computer to work with but slower for a programmer. You will have to find that value with a loop or some other means, then set that position to null. You will end up with an empty space in the array. You could reallocate the array etc etc...
What is easier to use for relatively small amounts of data is a List. You can do myList.RemoveAt(100); and it will work nicely.
You can not delete it.You can recreate the array or I advice you to use List<string> for the same.
List<string> columns = new List<string>();
columns.RemoveAt(1);
It will remove the 2nd element from your List<String> columns
i used
double [,] marks=new double[26,5]
int[] function = object.verify(marks)
public void verifymarks(double[][] marks)
error i get is cannot convert from double[,] to double[][]
i tried to search in the internet but couldnot find any solution. I have just began to use c#. Please Help. THankx in advance
double[][] is jagged. It's literally an array of arrays.
double[,] is multidimensional. It gets special compiler treatment.
They have different memory layouts. double[][] is an array which holds references to the other arrays, while double[,] is laid out single-dimensionally for easier use.
Another difference is what data they can hold. A jagged array can be like this:
1231243245345345345345
23423423423423
2342342343r234234234234234234
23423
While a multidimensional array has to be a perfect table, like this:
34534534534534
34534534534533
34534534534534
34534534534545
A way to get around it would be to use nullable ints.
Now, to solve your problem:
Change your method signature to public void verifymarks(double[,] marks) and in the method change anything that uses marks[x][y] to marks[x,y].
double[][] is called a Jagged array. It is an array of array (the same way you could create a list of list). With this structure you can specify a different size for each sub-array.
For exemple:
double[][] jaggedArray = new double[2][];
jaggedArray[0] = new double[5];
jaggedArray[1] = new double[151];
The other writing double[,] is a 2D array (Multidimensional array in general). You can see it as a table.
A very handy feature of multidimensional array is the initialization:
string[,] test = new string[3, 2] { { "one", "two" },
{ "three", "four" },
{ "five", "six" } };
Here's a visual, from LINQPad's Dump() function.
The first is the double[,], which creates a matrix. The second is double[][], which is just an array of arrays.