Can't do arithmetical operations on array values in c# - c#

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)
{
}

Related

Duplicating an array so it becomes unaffected c#

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.

Arrays getting changed inside irrelevant object

For my end of year project I need to develop an image processing and artificial intelligence application.
My image processing is already done, so I'm moving to the AI. However I have a problem here.
I will try to describe the situation here.
For a correct image processing I need an AI that can validate the board through the rules of checkers. So I need to check the current state of the play field with the last known state.
So for this I created an object with the currentBoard 2 dimensional array, and a method that validates the raw input of the board with the currentBoard (= last known state).
However, when another object -- my image processing object -- is finished with his method, it will change the array currentBoard in my AI object.
This is the same for a new array I created inside the main form. I think this happens cause of the heap/stack.
I hope I made my problem clear and understandable. I know I'm not the best in describing situations so please tell me when you don't understand a part completely.
Arrays are reference types, so, as you've found, changing the array contents in one place will change it for any other code which holds a reference to the same object.
To avoid changing the array, you should take a deep copy of your 2 dimensional array and work with the copy instead. Note that we have to take a deep copy of both the array and its internal arrays:
int[][] original = {new[] {1,2,3}, new[] {4,5,6}};
int[][] deepCopy = new int[original.Length][];
for (int index = 0; index < original.Length; index++)
{
var row = original[index];
int[] rowCopy = new int[row.Length];
row.CopyTo(rowCopy, 0);
deepCopy[index] = rowCopy;
}
You can also produce the same result using some simple linq:
int[][] deepCopyLinq = original.Select(x => x.ToArray()).ToArray();

Declaring an array with incremental values - is there a shortcut?

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

How to pass array in C#

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);
?

Array of an unknown length in C#

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];

Categories

Resources