Archangels
Archangels

Reputation: 87

Is there a way to access an list element property through another class

I have the following code:

public class settings
{
    public appConfig conf = new appConfig();

    public void getUserID(int listIndex, int newID)
    {
        conf.users[listIndex].ID = newID;
    }

    private class appConfig {
        public List<user> users;

        public appConfig()
        {
            users = new List<user>();
        }
    }
}

public class user {
    public int ID;
}

So with that code I use

var set = new settings();
set.setUserID(0, 20);

How can I change the code so I can access it like this:

var set = new settings();
set.userPropertys(listIndex).ID = newID;

How should I declare the userPropertys ? Is it a method or a new class or what?

Upvotes: 3

Views: 68

Answers (2)

sujith karivelil
sujith karivelil

Reputation: 29006

Yes you can do like this if userPropertys is a method that returns an object of type user. if so the signature will be like this:

public user userPropertys(int listIndex)
{
   return conf.users[listIndex];
}

And the usage will be like the following:

int listIndex = 0;
int newID = 12;
var set = new settings();
set.userPropertys(listIndex).ID = newID ;

Could you please verify this suggestion with the help of this working Example

Upvotes: 2

Peter Duniho
Peter Duniho

Reputation: 70652

If I understand correctly, instead of having to call the setUserID() method, you want a way to retrieve the user object and modify its property directly. There are at least two obvious ways to do this (misspelled names in code retained for clarity):

public class settings {
    public config conf = new config();
    public void setUserID(int listIndex, int newID) {
        conf.users[listIndex].ID = newID;
    }

    public user userPropertys(int index) { return conf.users[index]; }

    private class config {
        public List<user> users;
    }
}

Used like this:

set.userPropertys(listIndex).ID = newID;

I.e. exactly as you show it in your question.

or…

public class settings {
    public config conf = new config();
    public void setUserID(int listIndex, int newID) {
        conf.users[listIndex].ID = newID;
    }

    public List<user> userPropertys { return conf.users; }

    private class config {
        public List<user> users;
    }
}

Used like this:

set.userPropertys[listIndex].ID = newID;

I.e. used with the square-bracket indexer syntax.

Note that the only "repair" I did to your original code was add the config type to the conf field declaration. You don't show any actual initialization of the config.users field, which of course you'd need if you expect to access the List<user> object. And I agree with Jon's recommendations regarding naming conventions and exposing (or rather, not exposing) fields as public members.

Upvotes: 2

Related Questions