Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array property syntax in C#

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?

like image 212
Gasoline Avatar asked Aug 11 '11 18:08

Gasoline


People also ask

What is the syntax of array in C?

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.

What is array and its syntax?

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).

What is property in array?

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.

What is array give syntax with example?

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


1 Answers

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; }
}
like image 106
Blindy Avatar answered Sep 18 '22 13:09

Blindy