Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Property to get value from List<string>

Tags:

c#

private List<string> _S3 = new List<string>();
public string S3[int index]
{
    get
    {
        return _S3[index];
    }
}

Only problem is I get 13 errors. I want to call string temp = S3[0]; and get the string value from the list with the particular index.

like image 887
David W Avatar asked Aug 07 '26 13:08

David W


1 Answers

You can't do that in C# - you can't have named indexers like that in C#. You can either have a named property, with no parameters, or you can have an indexer with parameters but no name.

Of course you can have a property with a name which returns a value with an indexer. For example, for a read-only view, you could use:

private readonly List<string> _S3 = new List<string>();

// You'll need to initialize this in your constructor, as
// _S3View = new ReadOnlyCollection<string>(_S3);
private readonly ReadOnlyCollection<string> _S3View;

// TODO: Document that this is read-only, and the circumstances under
// which the underlying collection will change
public IList<string> S3
{
    get { return _S3View; }
}

That way the underlying collection is still read-only from the public point of view, but you can access an element using:

string name = foo.S3[10];

You could create a new ReadOnlyCollection<string> on each access to S3, but that seems a little pointless.

like image 61
Jon Skeet Avatar answered Aug 11 '26 14:08

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!