I have a a class that has an integer array property and I am trying to figure out the right syntax for it. The integer array gets instantiated in the class constructor.
class DemoClass
{
private int[] myNumbers;
public int[] MyNumbers
{
get { /* Some logic */ }
set { /* Some logic */ }
}
public DemoClass(int elements)
{
// Here, the array should get instantiated using the elements.
}
}
How does the get/set block syntax work if I want my client code to retrieve a number from the array through the property MyNumbers
?
How can I send it the right index?
What do I have to initialize?
To create an array, define the data type (like int ) and specify the name of the array followed by square brackets []. To insert values to it, use a comma-separated list, inside curly braces: int myNumbers[] = {25, 50, 75, 100}; We have now created a variable that holds an array of four integers.
An array is a collection of elements of the same type placed in contiguous memory locations that can be individually referenced by using an index to a unique identifier. Five values of type int can be declared as an array without having to declare five different variables (each with its own identifier).
To set the values in an array property, the user needs a control that allows selection of multiple values. When the user submits the form, the selected values are written to array elements. A form can set values in an array property through a grouped set of checkboxes or a multiple-selection list box.
An array is a variable that can store multiple values. For example, if you want to store 100 integers, you can create an array for it. int data[100];
Are you looking for:
class DemoClass
{
public int[] MyNumbers { get; private set; }
public DemoClass(int elements)
{
MyNumbers = new int[elements];
}
}
As for normal properties that do nothing except publicize a private field (as you seem to want):
private int[] myNumbers;
public int[] MyNumbers
{
get { return myNumbers; }
set { myNumbers = value; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With