Lakus
Lakus

Reputation:

How to Update a generic list passed by reference to a method?

I have a generic list of messages, which I pass to a method by reference. The method uses one of the messages from the list and updates the message.

How do I get this message updated with a new text, when passing the entire list by reference?

e.g.

private int RetrieveAndProcessQueueEntityRows(
        string sEntityCode,
        string sMessageFIDs,
        int iNumberToFetch,
        ref List<Entity> oMessageList) {

////......

Message currMessage = null;

foreach (Message oMessage in oMessageList) {
     if (oMessage.Message_UID == oPatientInfoEntityCurrent.MessageFID) {
        currMessage = oMessage;
        break;
     }
}

So now I can use the currMessage object to do the required updates. But how do I update the List<Entity> oMessageList with the currMessage?

Thanks for all your help! - Lakus

Upvotes: 2

Views: 2353

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062580

If the message is a class, you don't need to pass any of it by reference; you simply either update the existing message object, or create a new message object and swap it in the list (via the indexer, or with Remove/Add).

You only need ref if you are creating a new list.

So if Message is a mutable class, just:

currMessage.SomeProperty = "some value"; // done

If not, use the oMessageList's indexer (or, as stated Add/Remove) - i.e.

oMessageList[index] = replacementMessage;

Note that if you do change the list contents during the foreach, the foreach iterator will almost certainly break; there are ways of handling that, but if you can: just update a property of the message itself.

Upvotes: 6

Related Questions