Defining constants in C# - c#

I'm C/C++ to C# developer.
I need to do something like below,
#define LEN 20
int data[LEN];
Since C# doesn't support #define, many forums suggests to declare a const variable. A const variable might help me for below, but not for above.
for (int a = 0; a < LEN; a++)
{
x += data[LEN - a - 1];
}
So, how do I use the constant for array declarations as well?

C# lets you create constants of several built-in types using const keyword.
Constants can be numbers, Boolean values, strings, or a null reference.
Here is a small example:
public class Demo {
public const int Length = 20;
public void Main(string[] args) {
var data = new int[Length];
for (var i = 0 ; i != Length ; i++) {
data[i] = 2*i + 3;
}
}
}
Note: C# naming guidelines suggest avoiding all-caps naming.

Actually you should use it for the instantiation of the array:
const int LEN = 20;
int[] data = new int[LEN];

you could do something like this
static readonly int LEN = 20;
static void Main(string[] args)
{
int[] data = new int[LEN];
for (int a = 0; a < LEN; a++)
{
int x = data[LEN];
}
}
please note that that date array will be default initialized to 0.
also, you will get System.IndexOutOfRangeException for int x = data[LEN]; because you are asking for the 20th index and there is no such index in the array

You should not use constants to declare an array length. Also, there are many data structures in C# that allow you to have a dynamic size array/list/dictionary...

Related

Store reference of an ushort in an array in c#

I would like to store reference of an ushort variable in an ushort array, so that the value of the variable changes when I change the values inside the ushort array. Here is my sample code which will give a clear picture of what I'm trying to achieve.
public void IndexSetter(List<int> indexVal,Rootobject objectVal)
{
ushort[] refereneArray = new ushort[8]
{
objectVal.index1, objectVal.index2,
objectVal.index3 , objectVal.index4,
objectVal.index5, objectVal.index6,
objectVal.index7, objectVal.index8
};
for(int j = 0; j< indexVal.Count;j++)
{
refereneArray[j] =(ushort) indexVal[j];
}
}
Instead of storing the values like from above code , I need to store the reference so that the changes in indexVal list reflect in the values of index1, index2.. etc
I´d suggest not to have 8 indexes with the exact same name (except a number). Give every member of your class a name describing what it´s ment to be, however index6 isn´t really self-explanatory.
Having said this what you can do is to have one array of indexes within your class itself:
class Rootobject
{
public int[] Indexes { get; set; }
}
Now you can access them as follows:
public void IndexSetter(List<int> indexVal, Rootobject objectVal)
{
for(int i = 0; i < indexVal.Count; i++)
objectVal.Indexes[index] = indexVal[i];
}
Or even shorter:
objectVal.Indexes = indexVal.Cast<ushort>().ToArray();
You can do it with unsafe code, using array of pointers like this:
static unsafe void IndexSetter(IList<ushort> indexVal, Rootobject objectVal) {
fixed (ushort* r1 = &objectVal.index1)
fixed (ushort* r2 = &objectVal.index2) {
ushort*[] refereneArray = {r1, r2};
for (int j = 0; j < indexVal.Count; j++) {
*refereneArray[j] = (ushort) indexVal[j];
}
}
}
Should you really do this in real application is another story. There is very high chance that there is a better way to solve your problem, but you didn't tell us what the actual problem is.
If perfomance is not critical - you can use reflection:
static void IndexSetter2(IList<ushort> indexVal, Rootobject objectVal) {
int i = 0;
foreach (var field in objectVal.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance)
.Where(c => c.Name.StartsWith("index") && c.FieldType == typeof(ushort))
.OrderBy(c => c.Name)) {
field.SetValue(objectVal, indexVal[i]);
i++;
}
}

Problems with array declaration without set size

In Microsoft Visual Studio (Community Edition of course) I have a simple C# program where I declare a simple array without a set size like so
int[] paths;
In a later part of the program I try to set parts of the array but it gives me an error
Use of unsigned local variable 'paths'
in this part of the program
for (int b = 0; b < 100; b++) {
paths[b] = b;
}
In conclusion, I suppose I'm wondering whether this problem that affects just me, or a problem of syntax. (I originated from Java which is half to blame how I ran into this question) I am willing to accept closure on whether this is possible or not,(If so source please) or If I'm just doing it wrong.(If so please provide a solution/suggestions in comments)
In C# Arrays are fixed size, and need to be initialized
var size = 100;
int[] paths = new int[size];
for (var b = 0; b < size; b++) {
paths[b] = b;
}
List is also another good thing for a C# beginner to know about, the difference between an array and a list, is that a List will resize itself for you automagically (I believe there is a very similar List class in Java)
var size = 100;
var paths = new List<int>();
for (var b = 0; b < size; b++) {
paths.Add(b);
}
You just declared the array, but you also need to create it before using it:
paths = new int[100];
You must follow the array declaration syntax.
int[] paths; //-> here you are declaring the paths array and your not creating array.
in memory it set paths array without its sizes. So you must set the size by creating this array as follows.
int[] paths = new int[10];
you can create and declare array like as follows, for to assign another array with it.
EG:
int[] arr1 = new int[] { 0,1,2,3,4,5,6,7};
int[] paths =arr1;
here arr1 size and data will be automatically assigned to paths array.
Firstly you are creating a variable but you have not assigned it at all, this is the reason for you error.
Secondly in C# arrays require a fixed size and can not be resized so when initializing a size must be provided, either explicitly as below or implicitly by initializing it with objects (see comments).
int[] paths; // declaration
paths = new int[100] // assignment, array initialized with a size of 100
// with objects
// paths = new int[] { 1, 2, 3 };
// declaration and assignment can also be merged into 1 line.
// i.e int[] paths = new int[100]
for (int b = 0; b < 100; b++) {
paths[b] = b;
}
you must declare and initialize the array element in your code like
int[] myInt = new int[100]
If you don't know the size before initialize you need to use List like
List<int> list = new List<int>();
list.Add(123);
list.Add(456);
list.Add(789);
Console.WriteLine(list[2]);
and it is necessary to use array and size of array is not fixed before initialize you need to follow below code but below code is wastage of memory usage and more execution process. so my recommend is use List instead of int[]
// Global Variable
int[] myInt;
int mySize = 1;
private void button1_Click(object sender, EventArgs e)
{
if (mySize > 1)
{
int[] tempInt = new int[mySize];
tempInt = myInt;
myInt = new int[mySize];
for (int i = 0; i < mySize - 1; i++)
{
myInt[i] = tempInt[i];
}
myInt[mySize - 1] = mySize;
}
else
{
myInt = new int[mySize];
myInt[mySize - 1] = mySize;
}
mySize++;
}

Fastest Way To Create an Array of a NumberSequence

I would like to create an array with of length X, and i would like the following 'inteligence'
if , for exemple, X = 6,
myArray[x] = [0,1,2,3,4,5]
For the moment, i do
int[] availableIndex = new int[DestructiblesCubes.Count];
for (var i = 0; i < availableIndex.Length; i++)
{
availableIndex[i] = i;
}
But, i'm curious, is there a better (the faster way to execute it) and/or the faster(the shortest char length) way?
Thanks :)
This is short way to implement this. Not the performance best solution.
Enumerable.Range(0, 10).ToArray()
MSDN description for Enumerable.Range
I think the fastest method uses the unsafe context together with a proper fixed pointer to the array, as demonstrated below:
/*const*/ int availableIndex_Length = 6;
int[] availableIndex = new int[availableIndex_Length];
unsafe {
fixed(int* p = &availableIndex[0]) {
for(int i = 0; i < availableIndex_Length; ++i) {
*(p+i) = i;
}
}
}
This can be refactored to a method, optionally inlined:
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static unsafe void FillRange(ref int[] array) {
int length = array.Length;
fixed(int* p = &array[0]) {
for(int i = 0; i < length; ++i) {
*(p + i) = i;
}
}
}
static void Main(string[] args) {
// Example usage:
int[] availableIndices = new int[6];
FillRange(ref availableIndices);
// Test if it worked:
foreach(var availableIndex in availableIndices) {
Console.WriteLine(availableIndex);
}
Console.ReadKey(true);
}
You could try this:
unsafe
{
int[] availableIndex = new int[DestructiblesCubes.Count];
int length = availableIndex.Length;
int n = 0;
fixed(int *p = availableIndex) {
while(n < length) *p++ = n++;
}
}
may be faster, depending on the optimization stage of your compiler.
The only optimisation I can see to apply to your code as it stands is to count down to zero, but any increase in performance will be tiny
int[] availableIndex = new int[DestructiblesCubes.Count];
for (var i = availableIndex.Length-1; i >= 0; i--)
{
availableIndex[i] = i;
}
Otherwise, especially if you're talking large arrays, one thing to try would be to create an array greater than your max envisioned value of DestructiblesCubes.Count and
Intialize that array as above, then use Array.Copy when you want the smaller array.
I would be confident that no code we hand roll will be faster than a single call to Array.Copy.
int[] availableIndex = new int[DestructiblesCubes.Count];
Array.Copy(LargeArray, availableIndex, availableIndex.Length);
Otherwise I can't think of anything that might be faster than the code you have.

displaying an array

i am trying to compile this code about arrays and classes in visual studio 2010 but i am having problems when running it an error(consoleapplication.Carray does not contain a constructor that takes 0 arguments)is displaying, may someone tell me what wrong i am doing the code only displays and array or is there any way i can do it????
code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
CArray CArray;
CArray nums = new CArray();
for (int i = 0; i <= 49; i++)
nums.insert(i);
nums.displayElements();
}
}
class CArray
{
private int[] arr;
private int upper;
private int numElements;
public CArray(int size)
{
arr = new int[size];
upper = size - 1;
numElements = 0;
}
public void insert(int item)
{
arr[numElements] = item;
numElements++;
}
public void displayElements()
{
for (int i = 0; i <= upper; i++)
Console.Write(arr[i] + " ");
}
public void clear()
{
for (int i = 0; i <= upper; i++)
arr[i] = 0;
numElements = 0;
}
}
}
OK, several problems. One you have a constructor that is requesting the size of the array, and your main program is not feeding that to the constructor. This is also problematic because you are using the size of the array in your displayelements() loop. This won't compile since your constructor takes an argument. You need to, at the very least, change your Main() program so that it feeds the size of your array to the constructor, which you have defined in your class CArray. Change the following:
CArray nums = new CArray(50); //since 50 is the length of your array
you have a constructor in your CArray class that takes an integer as a parameter (int size). You are not passing that value to your CArray class in your main method.
static void Main()
{
int size = 33; //<-- declare an integer "size"
CArray nums = new CArray(size); // <-- make an array with a size of "size", in this case, 33
for (int i = 0; i <= size-1; i++) // <-- fill the integer with "size" numbers
nums.insert(i);
nums.displayElements();
}
i also would not hard code the size in the for loop you posted in your example.
right now you're saying for (int i = 0; i <= 49; i++) which basically ignores the size of the array you are supposed to pass along to the constructor.
if you use the example i've posted, you will always have an array of x elements.
If you leave the i <= 49 bit and your size is , lets say 100, then your displayElements method will print out the numbers from 0 to 49, followed by a whole bunch of 0's. I dont think that's what you want ^^

Redim Preserve in C#?

I was shocked to find out today that C# does not support dynamic sized arrays. How then does a VB.NET developer used to using ReDim Preserve deal with this in C#?
At the beginning of the function I am not sure of the upper bound of the array. This depends on the rows returned from the database.
VB.NET doesn't have the idea of dynamically sized arrays, either - the CLR doesn't support it.
The equivalent of "Redim Preserve" is Array.Resize<T> - but you must be aware that if there are other references to the original array, they won't be changed at all. For example:
using System;
class Foo
{
static void Main()
{
string[] x = new string[10];
string[] y = x;
Array.Resize(ref x, 20);
Console.WriteLine(x.Length); // Prints out 20
Console.WriteLine(y.Length); // Still prints out 10
}
}
Proof that this is the equivalent of Redim Preserve:
Imports System
Class Foo
Shared Sub Main()
Dim x(9) as String
Dim y as String() = x
Redim Preserve x(19)
Console.WriteLine(x.Length)
Console.WriteLine(y.Length)
End Sub
End Class
The two programs are equivalent.
If you truly want a dynamically sized collection, you should use List<T> (or something similar). There are various issues with using arrays directly - see Eric Lippert's blog post for details. That's not to say you should always avoid them, by any means - but you need to know what you're dealing with.
Use ArrayLists or Generics instead
Use a List<T>. It will dynamically size as needed.
You really shouldn't be using ReDim, it can be very expensive. I prefer List(Of T), but there are many options in this area.
That said, you had a question and here is your answer.
x = (int[]) Utils.CopyArray((Array) x, new int[10]);
I couldn't help but notice that none of the above answers approach the concept of multidimensional arrays. That being said, here's an example. The array in question is predefined as x.
int[,] temp = new int[newRows, newCols];
int minRows = Math.Min(newRows, x.GetUpperBound(0) + 1);
int minCols = Math.Min(newCols, x.GetUpperBound(1) + 1);
for (int i = 0; i < minRows ; ++i)
for (int j = 0; j < minCols; ++j)
temp[i, j] = x[i, j];
x = temp;
Just for fun, here's one way to use generics in order to redim/extend a unidimensional array (add one more "row") :
static T[] Redim<T>(T[] arr, bool preserved)
{
int arrLength = arr.Length;
T[] arrRedimed = new T[arrLength + 1];
if (preserved)
{
for (int i = 0; i < arrLength; i++)
{
arrRedimed[i] = arr[i];
}
}
return arrRedimed;
}
And one to add n rows (though this doesn't prevent user from undersizing the array, which will throw an error in the for loop) :
static T[] Redim<T>(T[] arr, bool preserved, int nbRows)
{
T[] arrRedimed = new T[nbRows];
if (preserved)
{
for (int i = 0; i < arr.Length; i++)
{
arrRedimed[i] = arr[i];
}
}
return arrRedimed;
}
I'm sure you get the idea.
For a multidimensional array (two dimensions), here's one possibility:
static T[,] Redim<T>(T[,] arr, bool preserved)
{
int Ubound0 = arr.GetUpperBound(0);
int Ubound1 = arr.GetUpperBound(1);
T[,] arrRedimed = new T[Ubound0 + 1, Ubound1];
if (preserved)
{
for (int j = 0; j < Ubound1; j++)
{
for (int i = 0; i < Ubound0; i++)
{
arrRedimed[i, j] = arr[i, j];
}
}
}
return arrRedimed;
}
In your program, use this with or even without the type specified, the compiler will recognize it :
int[] myArr = new int[10];
myArr = Redim<int>(myArr, true);
or
int[] myArr = new int[10];
myArr = Redim(myArr, true);
Not sure if all this is really relevant though. =D
Please feel free to correct me or improve my code. ;)
Even though it's a long time ago it might help someone looking for a simple solution - I found something great in another forum:
//from Applied Microsoft.NET framework Programming - Jeffrey Richter
public static Array RedimPreserve(Array origArray, Int32 desiredSize)
{
System.Type t = origArray.GetType().GetElementType();
Array newArray = Array.CreateInstance(t, desiredSize);
Array.Copy(origArray, 0, newArray, 0, Math.Min(origArray.Length, desiredSize));
return newArray;
}
Source: https://social.msdn.microsoft.com/Forums/en-US/6759816b-d525-4752-a3c8-9eb5f4a5b194/redim-in-c?forum=csharplanguage

Categories