David W
David W

Reputation: 1941

Use Property to get value from List<string>

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.

Upvotes: 3

Views: 5643

Answers (6)

jmshapland
jmshapland

Reputation: 483

_S3[i] should automatically return the string at position i

So just do:

string temp = _S3[0];

Upvotes: 0

LarsTech
LarsTech

Reputation: 81635

C# cannot have parameters for their properties. (Side note: VB.Net can though.)

You can try using a function instead:

public string GetS3Value(int index) {
  return _S3[index];
}

Upvotes: 2

Orn Kristjansson
Orn Kristjansson

Reputation: 3485

I would just go with

class S3: List<string>{}

Upvotes: -1

parapura rajkumar
parapura rajkumar

Reputation: 24413

You have to use this notation

 public class Foo
    {
        public int this[int index]
        {
            get
            {
                return 0;
            }
            set
            {
                // use index and value to set the value somewhere.   
            }
        }
    }

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1501926

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.

Upvotes: 7

Bhavik Goyal
Bhavik Goyal

Reputation: 2796

Try this

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

Upvotes: -1

Related Questions