We declare multi-dimension array in C# as
Datatype[,] <arrayname> = new Datatype[size,size];
I was just wondering what's the role of subscript operator[,] here. Can someone explain above syntax how it works exactly?
Datatype[,] identifier;
delclares a two-dimensional array of Datatype. The general syntax is, for n dimensions you put n - 1 commas (,) between the square brackets. For example for a four-dimensional array, put three commas:
Datatype[,,,] identifier;
When you instantiate the array you have to set the size of each dimension, e.g.:
int sizeDimOne = 5, sizeDimTwo = 10, sizeDimThree = 10;
Datatype[,,] identifier = new Datatype[sizeDimOne, sizeDimTwo, sizeDimThree];
As part of a declaration, this part:
[,]
means "2-dimensional array", a rectangular array that will have 2 dimensions. You can call them "width" and "height" or whatever you wish, but 2 there is.
The number of commas denote the number of dimensions, minus 1, meaning that to declare a 3-dimensional array you would use 2 commas:
Datatype[,,] = ...
Object initialization in C# occurs in two step:
1)Create reference to the required type i.e int []num
2)Allocating physical memory of that object type i.e new num[2]
The subscript operator on the left-hand side gives an indication to the CLR that object that is currently being allocated to memory is fully compatible with the type of physical object that is being allocated memory.
For multidimensional array, each comma adds a dimension to array
For 1-D array []
2-D Array [,]
3-D Array[,,]
Related
I am new to programming. While learning the data structure Array, I came to know that we have to initialize the array with the size, while creating one. But I also saw a code snippet in one of the sites which i make use to learn coding. The code is as follows
int[] ar = Array.ConvertAll(Console.ReadLine().Split(' '), arTemp => Convert.ToInt32(arTemp))
I guess the code is to read the input from the console(which is a string) and splits it into substrings and then convert into integer array and gets stored in 'ar'.
My question is that there were no errors on this line. But the array size is not mentioned before using them. How is that? where do the size of this array gets initialized in this case?
From MSDN:
Array.ConvertAll(): Converts an array of one type to an array of another type.
where do the size of this array gets initialized in this case?
In Array.ConvertAll() static function, Size array is based on your input array.
In your case input array is Console.ReadLine().Split(' '). Split(' ')returns an array of space seperated words. Size of this array get assigned to the output of Array.ConvertAll() function
int[] ar = Array.ConvertAll(Console.ReadLine().Split(' '), arTemp => Convert.ToInt32(arTemp))
//+ +++++++++++++ ++++++++++++++++++++++++ ++++++
//| | | |
//| | | + Integer convertor
//| | |
//| | + Input array with it's size
//| |
//| + Converting input array to array of type int
//|
//+ Output integer array
int ar is a reference to an array. The array size is determined at runtime. Array.ConvertAll(...) returns an array, the actual object. This new array created is linked to the ar variable.
I need to generate a 4 bit string randomly and set to a property via Linq.
Right now is hardcoded:
// TODO: hardcode bit string
employees = employees.Select(x => { x.Options = "0101"; return x; }).ToList();
I need Options to be random so I can get all 4 bit possible values: "0001","0010", "0011" and so on.
I was thinking on having a Random 0 to 1 variable and generate the value 4 times and concatenate the string.
Any clue on how to implement this?
If speed is critical, such as this operating being called in a loop, it would be more efficient to use a 16 element string array of all possible values and select the element randomly.
var rand = new Random();
Convert.ToString(rand.Next(16), 2).PadLeft(4, '0')
Explanation:
The first line creates a random object, nothing too hard to understand here... The second line first generates a random number between 0 - 15 (rand.Next(16)). Then it puts the random number into Convert.ToString. The method converts to number to base 2 (because the second parameter is 2). However, this still is not enough because if the random number can be represented by 3 bits or fewer, the returned string will not have the leading 0s. That's why I used PadLeft to add them in.
You can use this
Convert.ToString(int, 2);
This will convert the int to base 2 string.
Where int is a random number up to 16 not included.
This might be a really beginer's question but I've been reading about this and I'm finding it hard to understand.
This is a sample from the msdn page about this subject (just a little smaller).
using System;
class SetByteDemo
{
// Display the array contents in hexadecimal.
public static void DisplayArray(Array arr, string name)
{
// Get the array element width; format the formatting string.
int elemWidth = Buffer.ByteLength(arr) / arr.Length;
string format = String.Format(" {{0:X{0}}}", 2 * elemWidth);
// Display the array elements from right to left.
Console.Write("{0,7}:", name);
for (int loopX = arr.Length - 1; loopX >= 0; loopX--)
Console.Write(format, arr.GetValue(loopX));
Console.WriteLine();
}
public static void Main()
{
// These are the arrays to be modified with SetByte.
short[] shorts = new short[2];
Console.WriteLine("Initial values of arrays:\n");
// Display the initial values of the arrays.
DisplayArray(shorts, "shorts");
// Copy two regions of source array to destination array,
// and two overlapped copies from source to source.
Console.WriteLine("\n" +
" Array values after setting byte 1 = 1 and byte 3 = 200\n");
Buffer.SetByte(shorts, 1, 1);
Buffer.SetByte(shorts, 3, 10);
// Display the arrays again.
DisplayArray(shorts, "shorts");
Console.ReadKey();
}
}
SetByte should be easy to understand, but if I print the shorts array before doing the SetByte operation the array looks like this
{short[2]}
[0]: 0
[1]: 0
After doing the first Buffer.SetByte(shorts, 1, 1); the array becomes
{short[2]}
[0]: 256
[1]: 0
And after setting Buffer.SetByte(shorts, 3, 10); the array becomes
{short[2]}
[0]: 256
[1]: 2560
At the end, in the example they print the array from right to left:
0A00 0100
I don't understand how this works, can someone give me to some information about this?
The Buffer class allows you to manipulate memory as if you were using a void pointer in c, it's like a sum of memcpy, memset, and so on to manipulate in a fast way memory on .net .
When you passed the "shorts" array, the Buffer class "sees" it as a pointer to four consecutive bytes (two shorts, each of them two bytes) :
|[0][1]|[2][3]|
short short
So the uninitialized array looks like this:
|[0][0]|[0][0]|
short short
When you do Buffer.SetByte(shorts, 1, 1); you instruct the Buffer class to change the second byte on the byte array, so it will be:
|[0][1]|[0][0]|
short short
If you convert the two bytes (0x00, 0x01) to a short it is 0x0100 (note as these are the two bytes one after other, but in reverse order, that's because the C# compiler uses little endianness), or 256
The second line basically does the same Buffer.SetByte(shorts, 3, 10);changes third byte to 10:
|[0][1]|[0][10]|
short short
And then 0x00,0x0A as a short is 0x0A00 or 2560.
The .NET types use little endianness. That means that the first byte (0th, actually) of a short, int, etc. contains the least significant bits.
After setting the array it seems like this as byte[]:
0, 1, 0, 10
As short[] it is interpreted like this:
0 + 1*256 = 256, 0 + 10*256 = 2560
i think the part that people might struggle with is that the Buffer.SetByte() method is basically iterating over the array differently than a regular assignment with the array indexer [], which would separate the array according to the width of the containing type(shorts/doubles/etc.) instead of bytes... to use your example:
the short array is usually seen as
arr = [xxxx, yyyy](in base 16)
but the SetByte method "sees" it as:
arr = [xx, yy, zz, ww]
so a call like Buffer.SetByte(arr, 1, 5) would address the second byte in the arry, which is still inside the first short. setting the value there and that's it.
the result should look like:
[05 00, 00 00] in hex or [1280,0].
I have a 2D array that I want to clear and reset to 0 values. I know how to clear a vector (1D array) using Array.Clear() but I don't know the best way to clear a 2D matrix.
double D = new double[10];
Array.Clear(D, 0, D.Length);
How does one clear a 2D N x M array
double D[,] = new double[N,M];
Thank you for any help you may be able to provide.
Array.Clear works with multidimensional arrays, too:
double[,] D = new double[M,N];
Array.Clear(D, 0, D.Length);
Note, there's no need to compute the length yourself, since the Length property returns the total number of elements, regardless of the number of dimensions:
A 32-bit integer that represents the total number of elements in all the dimensions of the Array; zero if there are no elements in the array.
You can use the same method, but you may have to calculate your real length parameter value:
double D[,] = new double[N,M];
Array.Clear(D, 0, M*N);
I would use M*N because it's more readable, and I don't know what Length property returns for 2-dimmentional array.
Just reallocate it.
double D[,] = new double[N,M];
creates a empty 2D array.
How do you use the Array.GetLength function in C#?
What is the difference between the Length property and the GetLength function?
GetLength takes an integer that specifies the dimension of the array that you're querying and returns its length. Length property returns the total number of items in an array:
int[,,] a = new int[10,11,12];
Console.WriteLine(a.Length); // 1320
Console.WriteLine(a.GetLength(0)); // 10
Console.WriteLine(a.GetLength(1)); // 11
Console.WriteLine(a.GetLength(2)); // 12
For 1-dimensional arrays Length and GetLength(0) are exactly the same.
For arrays of higher rank Length is the product of all GetLength(0..Rank-1) values, in other words it is always the total number of fields.
The .Length property returns the number of elements in an array, whether it be one dimensional or multidimensional. That is a 2x6 array will have length of 12.
The .GetLength(0) method returns number of elements in the row direction in a multidimensional array. For a 2x6 array that is 2.
The .GetLength(1) method returns number of elements in the column direction in a multidimensional array. For a 2x6 array that is 6.
These do not return an actual element value, as stated by the chosen answer above.
GetLength returns the length of a specified dimension of a mulit-dimensional array.
Length returns the sum of the total number of elements in all the dimensions.
For a single-dimensional array, Length == GetLength(0)
For a two-dimensional array, Length == GetLength(0) * GetLength(1)
etc.
In mathematical term, we call as m rows and n columns, so the results is product of m*n for a two dimensional array. In this case GetLength(0) = m rows and GetLength(1)= n columns. For e.g see below example
string[,] stocks ={{"RELIND","Reliance Industries","1006.30"},{"TATMOB","Tata Mobiles","504.10"},{"ALST","Allstate","800.00"}, {"GE","GE Motors","810.00"}
};
The stocks arrays return GetLength(0)= 4 and GetLength(1)=3 and length =12