tags:

views:

554

answers:

2

Hello all,

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

+6  A: 

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.

Marc Gravell
A: 

Hi Marc, Thanks for your quick response. I am new to using generics. Could you show how I could solve this, with the code I have provided.

Yes.. Message is a class..

For Instance, what would I write outside the foreach loop to update the List. Considering currMessage is an updated message for the message with ID=7 in the oMessageList.

THanks again. - Lakus

Is it a new message, or have you simply updated the existing message? And can you clarify the message/entity confusion?
Marc Gravell
Oh : and what runtime are you using? 3.5? 2.0? There are cleaner approaches depending on which version...
Marc Gravell