Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Property to get array element in C#

Is there a way to get a specific element (based in index) from a string array using Property. I prefer using public property in place of making the string array public. I am working on C#.NET 2.0

Regards

like image 273
kobra Avatar asked Dec 01 '22 11:12

kobra


2 Answers

Are you possibly trying to protect the original array; do you mean you want a protective wrapper around the array, through "a Property" (not of its own)? I'm taking this shot at guessing the details of your question. Here's a wrapper implementation for a string array. The array cannot be directly access, but only through the wrapper's indexer.

using System;

public class ArrayWrapper {

    private string[] _arr;

    public ArrayWrapper(string[] arr) { //ctor
        _arr = arr;
    }

    public string this[int i] { //indexer - read only
        get {
            return _arr[i];
        }
    }
}

// SAMPLE of using the wrapper
static class Sample_Caller_Code {
    static void Main() {
        ArrayWrapper wrapper = new ArrayWrapper(new[] { "this", "is", "a", "test" });
        string strValue = wrapper[2]; // "a"
        Console.Write(strValue);
    }
}
like image 72
John K Avatar answered Dec 03 '22 00:12

John K


If I understand correctly what you are asking, You can use an indexer. Indexers (C# Programming Guide)

Edit: Now that I've read the others, maybe you can expose a property that returns a copy of the array?

like image 26
Fredy Treboux Avatar answered Dec 03 '22 01:12

Fredy Treboux