I have tried
int[] secondArray = firstArray;
but whenever I alter the first array it changes in the second, is there a function that allows me to alter the first without it affecting the second?
Thanks.
That's because you have an object that is an "array of integer" which firstArray references. Your assignment statement just increments the reference count of the object
I think what you may be looking for is a way to provide a shallow copy of the firstArray? If so, use the clone method
Like Tim said, you need to understand why this happens, so read up on it. :)
But you could use the Array.CopyTo method:
int[] firstArray = new int[20];
int[] secondArray = new int[20];
firstArray.CopyTo(secondArray, 0);
But you will have to make sure that you wont overflow the second array yourself, because otherwise, it will throw an exception.
Related
I have an array with 3 integers. I want to duplicate the array and change the first integer. For some magical reason, BOTH arrays get their first integer adjusted. I have no idea why this is happening and it's driving me crazy.
int [] numbers1 = {1, 2, 3}
int [] numbers2 = {3, 4, 5}
numbers2 = numbers1;
At this point I did a System.Console.Writeline to see both arrays are now {1, 2, 3}. So far so good.
numbers1[0] = 4;
When I'm doing a System.Console.Writeline I see BOTH arrays now look like {4, 2, 3}. I want numbers2 to stay the same.
Currently you are only passing a reference. The numbers in the array are stored in memory. When you reference an object in memory it points to that object. It does not create a new object in memory when referencing, so you need to clone the ints into another array so that it points to a different object in memory.
numbers2 = numbers1;
You need to clone the arrays.
numbers2 = (int[])numbers1.Clone();
As others have noted you can also use the .ToArray() method. This creates a copy of the items in the array.
numbers2 = numbers1.ToArray();
Arrays are a reference-type, regardless if the values of an array are value-types.
When you allocate an array you are creating a block of memory that the array variable points to. When you assign one array variable to another you are assigning the memory reference, not the values in the array. So both of your numbers1 and numbers2 arrays are pointing to the same set of values.
Now this should make sense. Imagine if you have an array with a million elements then every time you assigned or passed the array around you made a copy it would be an horrific performance issue.
So, you need to explicitly say when you want to copy an array.
The easiest way is to do this:
numbers2 = numbers1.ToArray(); // yes, this copies the entire array.
Using this:
numbers2 = numbers1;
You are assigning the reference of first array to the second array. So it loses your original contents and start pointing to numbers1. If you want to copy few or all items of numbers1 to numbers2 then either use Clone() or use loop to copy elements.
Did you try .ToArray() method? It will create new array not assign by reference Array2= Array.ToArray(); Click here for more about .ToArrray()
try to use the .ToArray(); or Clone its work for me
my suggestion is .ToArray();
I'm writing a program for homework, but I have stumbled upon a very hard problem for me.
Now, I'm pretty new to C#, so please bear with me. This may be really easy and obvious.
On-topic:
C# doesn't allow me to perform arithmetical operations on multidimensional array values:
if(map[0,1] - map[0,0] == 10)
This statement doesn't return a value, but instead throws me an error:
Object reference not set to an instance of an object.
You need to first declare the array. Example:
var map = new int[2,2];
creates a two-dimensional array with four integer elements.
the error sounds like you didn't initiate the values of the array
also don't forget that you took [,] arrays
int[,] example = new int[,] { {11,5}, {1,10} };//initiate the array
if (example[0,0]-example[1,0] == 10)
{
}
This question is probably pretty stupid, but I'm new to C# and I'm not sure if there are any shortcuts to do this. I have a dynamic array for which the range will always be 1-n, with n being variable. Is there anyway to declare an array and have it hold incremental values without looping?
Think along the lines of my array holding values 1-50. I'd like to declare an array as such (logically): double[] myArray = new double[] {1-50} or, more generically for my purposes double[] myArray = new double[] {1-n}. I don't know what made me think of this, I just thought I'd ask.
I am going to bind this array (or list) to a combo box in WPF. I guess setting a combo-box the same way would also work if there's a shortcut for that.
Sorry for the dumb question. =)
int n = 50;
var doubleArray = Enumerable.Range(1, n).Select(x => (double)x).ToArray();
That will generate a sequence of integers from 1 to n (in this case 50) and then cast each one to a double and create an array from those results.
You could use a List<T> which represents a dynamic array to which you could add elements.
System.Linq.Enumerable.Range can generate än enumeration of int. Cast the enumeration if you really want double.
System.Linq.Enumerable.Range(1,20).ToArray()
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.range.aspx
I have a prototype:
int[] medianFileter(int[] data);
and an array
int[] intVal = new int[5];
How can I pass the intVal to the prototype in C#?
Um, you just call it (assuming you've got a real implementation to call):
int[] result = medianFileter(intVal);
Note that any changes made to the array within the method will show up in intVal: you're not passing each of the integers individually, but a reference to the whole array.
(There could be some trickiness here due to your use of the word "prototype" - it's not standard C# terminology, so I'm not exactly sure what you mean. If you could clarify the question, that would help.)
On a side note, method names in .NET are usually Pascal-cased, so this should probably be:
int[] result = ApplyMedianFilter(intVal);
It's either I don't see some obvious weirdness here, or it's just usual function invocation:
int[] medianFiltered = medialFileter(intVal);
This is what you would do,
medianFileter(intVal);
What's the problem with:
medianFileter(intVal);
?
I've just started learning C# and in the introduction to arrays they showed how to establish a variable as an array but is seems that one must specify the length of the array at assignment, so what if I don't know the length of the array?
Arrays must be assigned a length. To allow for any number of elements, use the List class.
For example:
List<int> myInts = new List<int>();
myInts.Add(5);
myInts.Add(10);
myInts.Add(11);
myInts.Count // = 3
Use List<> to build up an 'array' of unknown length.
Use List<>.ToArray() to return a real array, and not a List.
var list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
var array = list.ToArray();
A little background information:
As said, if you want to have a dynamic collection of things, use a List<T>. Internally, a List uses an array for storage too. That array has a fixed size just like any other array. Once an array is declared as having a size, it doesn't change. When you add an item to a List, it's added to the array. Initially, the List starts out with an array that I believe has a length of 16. When you try to add the 17th item to the List, what happens is that a new array is allocated, that's (I think) twice the size of the old one, so 32 items. Then the content of the old array is copied into the new array. So while a List may appear dynamic to the outside observer, internally it has to comply to the rules as well.
And as you might have guessed, the copying and allocation of the arrays isn't free so one should aim to have as few of those as possible and to do that you can specify (in the constructor of List) an initial size of the array, which in a perfect scenario is just big enough to hold everything you want. However, this is micro-optimization and it's unlikely it will ever matter to you, but it's always nice to know what you're actually doing.
You can create an array with the size set to a variable, i.e.
int size = 50;
string[] words = new string[size]; // contains 50 strings
However, that size can't change later on, if you decide you need 100 words. If you need the size to be really dynamic, you'll need to use a different sort of data structure. Try List.
Use an ArrayList if in .NET 1.x, or a List<yourtype> if in .NET 2.0 or 3.x.
Search for them in System.Collections and System.Collections.Generics.
You might also want to look into Dictionarys if your data is unique, This will give you two columns to work with.
User name , Total bill
it gives you a lot of built in tools to search and update just the value.
var yummy = new List<string>();
while(person.FeelsHappy()) {
yummy.Add(person.GetNewFavoriteFood());
}
Console.WriteLine("Sweet! I have a list of size {0}.", list.Count);
Console.WriteLine("I didn't even need to know how big to make it " +
"until I finished making it!");
try a generic list instead of array
In a nutshell, please use Collections and Generics.
It's a must for any C# developer, it's worth spending time to learn :)
As detailed above, the generic List<> is the best way of doing it.
If you're stuck in .NET 1.*, then you will have to use the ArrayList class instead. This does not have compile-time type checking and you also have to add casting - messy.
Successive versions have also implemented various variations - including thread safe variants.
If you really need to use an array instead of a list, then you can create an array whose size is calculated at run time like so...
e.g i want a two dimensional array of size n by n. n will be gotten at run time from the user
int n = 0;
bool isInteger = int.TryParse(Console.ReadLine(), out n);
var x = new int[n,n];