This question already has answers here:
Adding values to a C# array
(26 answers)
Closed 9 years ago.
How can i create a int array in class.
And i have to add values to that array.
Not to a specific key.
i declared array as
public int[] iArray;
from function i have to insert values of i to array. My i values gets change. So i have to save those in a array.
iArray[] = i;
But it shows error.
Handling arrays is pretty straight forward, just declare them like this:
int[] values = new int[10];
values[i] = 123;
However, arrays in C# have fixed size. If you want to be able to have a resizeable collection, you should use a List<T> instead of an array.
var values = new List<int>();
values.Add(123);
Or as a class property:
class SomeClass
{
private List<int> values = new List<int>();
public List<int> Values { get { return this.values; } }
}
var someInstance = new SomeClass();
someInstance.Values.Add(123);
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");
This question already has answers here:
Return multiple values to a method caller
(28 answers)
Closed 5 years ago.
I want to define a function with two outputs. The first one is a boolean variable and the second one is 2D array with unknown numbers of rows and columns but the array will be defined if the boolean variable is true and if the boolean variable is false, the array is not defined. how can I define this function? I am thankful if anybody can exemplify it in an example.
Thanks
You want something like this .
Tuple<string, int> NameAndId()
{
// This method returns multiple values.
return new Tuple<string, int>("Test", 100);
}
Why not return null if array is not defined?
public static bool MyMethod(out int[,] array) {
array = null;
...
}
....
int[,] data;
if (MyMethod(out data)) {
....
}
Or in case of C# 7.0+
if (MyMethod(out var data)) {
....
}
Edit: if you want to return an array, but you don't know its Length (or want to adjust it) you can try working with List<T> and put .ToArray() in the end:
using System.Linq;
...
List<int> list = new List<int>();
list.Add(1);
list.Add(5);
list.Add(10);
...
list.Remove(5);
...
list.RemoveAt(0);
...
array = list.ToArray();
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
i am very new to C# programming so my question may sound very silly
actualy i am creating an multidimensional string array like
public class master
{
public List<string> user_selected = new List<string>();
public List<string> available = new List<string>();
public List<string> bookedseats = new List<string>();
public string [] [] trackbooked=new string[30][] ;
}
now i am assigning some values to it like
a[l].trackbooked[i][j] = pb.Name;
a is a list of object
List<master> a = new List<master>();
a.Add(obj0);
a.Add(obj1);
a.Add(obj2);
a.Add(obj3);
a.Add(obj4);
can some one plz help.thank u in adv.
You've only initialized one dimension of your multidimensional array. See msdn for all the ways you can initialize a multidimensional array.
public string [,] trackbooked=new string[30,30] ;
pb.Name.Tostring();
I would venture to guess that whatever pb is that its NAME value isn't returned as a string. You should be able to use the above command to correct your issue.
static int[] scores = new int[100];
static int[] scorescopy;
public static int orderscores()
{
scorescopy = scores;
Array.Sort(scorescopy);
int sortingtoolb = 0;
return 0;
}
I am trying to get a copy of my initial array and then trying to sort that copy. However, when I use the Array.Sort() function, my first array keeps on being sorted as well, but I would like to preserve it. I tried taking away the new declaration on the scorescopy and that did not effect the result.
Also, is there a way to keep my unused variables within the array as null? (if I am not using all parts of it, I get a bunch of 0's in the beginning of the array).
I am using Visual Studio Express 2012 for Windows 8 on a system running Windows 8.1 Pro.
An array, when assigned, only copies a reference to the same array in memory. You need to actually copy the values for this to work:
public static int orderscores()
{
scorescopy = scores.ToArray(); // Using LINQ to "cheat" and make the copy simple
Array.Sort(scorescopy);
int sortingtoolb = 0;
return 0;
}
Note that you can do this without LINQ via:
scorescopy = new int[scores.Length];
Array.Copy(scores, scorescopy, scores.Length);
//... rest of your code
The expression scorescopy = scores; duplicate the handle to the array.
if you want to create a copy of the array items you should change that line to:
scores.copyTo(scorescopy,0);
You still need to make sure scorecopy has enough room to store the items.
so you also need this expression: static int[] scorescopy = new int[scores.Length];
and now your code should like this:
static int[] scores = new int[100];
static int[] scorescopy = new int[scores.Length];
public static int orderscores()
{
scores.copyTo(scorescopy,0);
Array.Sort(scorescopy);
int sortingtoolb = 0;
return 0;
}
You are getting a pointer to the same array, you want a clone:
scorescopy = (int [])scores.Clone();
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Remove element of a regular array
I have a method defined which returns class array.
ex: Sampleclass[]
The Sampleclass has properties Name, Address, City, Zip. On the client side I wanted to loop through the array and remove unwanted items. I am able to loop thru, but not sure how to remove the item.
for (int i = 0; i < Sampleclass.Length; i++)
{
if (Sampleclass[i].Address.Contains(""))
{
**// How to remove ??**
}
}
Arrays are fixed size and don't allow you to remove items once allocated - for this you can use List<T> instead. Alternatively you could use Linq to filter and project to a new array:
var filteredSampleArray = Sampleclass.Where( x => !x.Address.Contains(someString))
.ToArray();
It's not possible to remove from an array in this fashion. Arrays are statically allocated collections who's size doesn't change. You need to use a collection like List<T> instead. With List<T> you could do the following
var i = 0;
while (i < Sampleclass.Count) {
if (Sampleclass[i].Address.Contains("")) {
Sampleclass.RemoveAt(i);
} else {
i++;
}
}