C# instantiate array value [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
For some reason this works
public void TestData(ref array[,])
{
array[0, 0] = new DataType();
}
while this doesn't work
public void TestData(ref array[][])
{
array[0][0] = new DataType();
}
I've found a way around needing to use the [][] array, but would be nice to know why it doesn't seem to work the same. Do I need to instantiate at the array[0] level as well?

type[,] is a 2-dimensional array, while type[][] is a 1-dimensional array of 1-dimensional arrays, sometimes called a jagged array, because the arrays are not necessarily the same length.
You can use either, depending on what makes sense. If you use a jagged array, you have to instantiate each of the arrays (the outer one and all of the inner ones). If you use a 2-D array, you just instantiate it once.

"Do I need to instantiate at the array[0] level as well?" yes.
So if you want to use T[][] then you need to do
for (int i = 0; i < array.Length; i++)
array[i] = new T[someSize];
So that is the basic reason why your "jagged" array isn't working. When you declare the other one it instantiates the horizontal arrays as well as the vertical one, in this case you only get the vertical one (column) and have to instantiate the rows yourself. The two aren't actually interchangeable even though working with them is fairly similar.

Related

C# What is the Use of Square Brackets ([]) when construction an Object in C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
the Question may be very basic, but I stumbeled across a line of Code I have never seen and was wondering what the use of the Square Brackets are.
public NodeItem (bool isWall, Vector2 pos, int x, int y)
{
this.isWall = isWall;
this.pos = pos;
this.x = x;
this.y = y;
}
1. private NodeItem[,] map;
2. map = new NodeItem[width, height];
Can someone explain to me how 1 and 2 work and what the advantage of this might be?
This is'nt an object. When you're using square brackets, you're declaring an array (unlike C and C++, you don't specify the numbers of elements. Instead, you do this when you initializing the array, with a new statement (new <Type>[<itemsNumber>])). An array is a set of objects, which any object should be initialized - any array element (the term to an item of the array) contains the object's default value - 0 for numbers, null for reference types and pointers, etc.. But when you're declaring an array, you save you a place in the memory to store the array elements (arrays are reference types, so they are stored in the heap). When you're using a comma inside an array declaration, you're declaring a multidimensional array. this is a matrix (for 2D array; it may be 3D, 4D, etc.) To access an array element, you specify in the square brackets all the indexes, separated by commas.
For more details about arrays in C# see https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/, and about multidimensional arrays - see https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/multidimensional-arrays.
In c#, x[] is an array of type x. x[,] is a two-dimensional array (and naturally, x[,,] is a three-dimensional array and so on).
So - private NodeItem[,] map; is declaring a field that is a two-dimensional array of NodeItem, named map.
The line after that - map = new NodeItem[width, height]; initialize the array - so it now contains width * height references to NodeItem, all implicitly initialized to default(NodeItem) - null for reference types, and whatever default value for value types.
For further reading, Arrays (C# Programming Guide) And Multidimensional Arrays (C# Programming Guide)

Is it possible to create a constructor for Arrays c#? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am new to coding and still at college at the moment. Sorry if this question has been asked before but I could not see it any where.
I was wonder if it is possible to create a constructor for the array Class, so each time I create a new array I can execute code such as count the amount of arrays I have in my application for each instance I make? I understand the Array class is abstract so you cannot make an instance of it.
Are int[] arrays just methods within the abstract Array class?
Any insight as to why it is or isn't possible would be greatly appreciated!
Thanks
If your custom code is just to populate the array, C# provides several built in ways to do this (see All possible C# array initialization syntaxes).
If you want to have code execute every time you create an instance of a particular kind of object, you should make a class that represents that object (you might be able to do an extension method as well, but that would likely get confusing over time). This class might be nothing more than a wrapper around an array:
public class MyArray<T>
{
private T[] _array;
public MyArray()
{
// execute your always must run code here!
}
public ArrVal
{
get { return _array; }
set { _array = value; }
}
}
...
MyArray<int> myArray = new MyArray<int>(); // your custom code gets executed when you new up the object here
However, per best practices, you should avoid having code in a constructor that does too much work (and in my experience, having a constructor that throws exceptions can cause some problems that are hard to debug, although MSDN says it's better to throw the exception than to cover it up). If this code is going to be doing intensive work, it may be better to create a separate method (maybe something called public void Initialize()) so that callers can new up the object more lazily.
You should also avoid trying to have this done for all arrays, because I can guarantee it'll cause problems for you or someone else down the road when they can't figure out why int[] arr = new int[3] is doing extra stuff. You should look to properly use encapsulation here instead (i.e. creating a wrapper/extension/decorator class).
Also, it's entirely possible that one of the existing .NET classes for Collections fulfills your needs... Look into those.
I'm not sure if I understand your question correctly, but if you want to be able to execute code when you create an array you can use LINQ:
int[] myArray = new int[10]
.Select((x, idx) => /*execute your code here*/).ToArray();
So you can create an array of length 10, then you can execute code for each element to determine what you want to populate it.
For example you could fill the array with random numbers using:
Random random = new Random();
int[] myRandomArray = new int[10]
.Select((x, idx) => random.Next()).ToArray();

Adding a new element to the end of a C# array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Im trying to do exactly what the title says
int[] weeks = {};
weeks[weeks.Length]=1;
this doesnt work. There is also no .Add Method.
Any ideas? or is this not possible
Line 1 declares and initializes a new 1-dimensional array of int without specific size.
Line 2 resizes the array (weeks) to its actual size, plus 1.
Line 3 assigns the value 1 to the element at the last position (that we created in Line 2)
Remember: int[5] weeks; -> to access last element you have to use index 4 -> weeks[4] = 1
int[] weeks = {};
Array.Resize(ref weeks,weeks.Length + 1);
weeks[weeks.Length - 1]=1;
Arrays in C# by definition are of a fixed size, and cannot be dynamically expanded.
I would suggest using a List<>, as they can be dynamically expanded, much like vectors in other programming languages.
List<int> weeks = new List<int>();
weeks.add(1);
See more here.
First of all there is no such thing razor array. Razor is a view engine and array is a data structure.
Arrays have fixed length so if you declare an array with the length of 5:
int[] weeks = new int[5];
Trying to add an element to a fifth place will result in IndexOutOfRangeException
If you need some data-structure with variable size you could look at all the objects that implement IList interface for example a List, an ArrayList and others.
IList interface also defines Add method that you requested.

re-initialize array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How can I re-initialize an array?
public int[] numbers;
In my case numbers will be set with an unknown-length array. For example, when I use it first, it will have 8 elements, next time only 5, then 12.
I read some about this topic, and found only one relevant:
http://social.msdn.microsoft.com/Forums/en-US/bee99ac8-4ade-40ac-aa78-8d14d1d7bf9f/c-reinitialize-arrays?forum=csharplanguage
Even if I do not care about the memory usage of redeclaration (uhh), I can't make it this way, since I'm going to use the array in a timer's thick method, and gonna use the same array, until the timer stops. Then call the function again, which would put the elements into the array, then start the timer again.
Edit:
There are 3 functions in my case and the array declare as a public variable. The first function is called doAction(), which calls another function which returns an array with unknown length. Then, doAction starts the timer1 (thick method), which needs to reach the array from doAction. That's the reason why I used a global variable to put the array in.
Of course you can do it that way. You cannot change the size of an array. When you stop the Timer, simply create a new array and assign it to the same variable. It's the variable that matters. You'll be getting the array from the variable in the Tick event handler so you'll always get the current array.
When you use it first, do
numbers = new int[5];
when you use it again, do
numbers = new int[12];
If it's not that simple, then you haven't explained your problem very well.

Is there a c# library that provides array manipulation like numpy [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
I am starting to use the Numpy and really like it's array handling capabilities. Is there some library that I can use in C# that provides similar capabilities with arrays. The features I would like most are:
Creating one array from another
Easy/trival iteration of arrays of n dimension
Slicing of arrays
NumPY has been ported to .NET via IronPython.
I don't think you need a library. I think LINQ does all you mention quite well.
Creating one array from another
int[,] parts = new int[2,3];
int[] flatArray = parts.ToArray();
// Copying the array with the same dimensions can easily be put into an extension
// method if you need it, nothing to grab a library for ...
Easy iteration
int[,] parts = new int[2,3];
foreach(var item in parts)
Console.WriteLine(item);
Slicing of arrays
int[] arr = new int[] { 2,3,4,5,6 };
int[] slice = arr.Skip(2).Take(2).ToArray();
// Multidimensional slice
int[,] parts = new int[2,3];
int[] slice = arr.Cast<int>().Skip(2).Take(2).ToArray();
The awkward .Cast<int> in the last example is due to the quirk that multidimensional arrays in C# are only IEnumerable and not IEnumerable<T>.

Categories