• Static list issue using modifying the same object Reference (pointer)

    Amit Member

    Static list issue using modifying the same object Reference (pointer)

  • Abhey Member

    You need to create a new ErrorMsgs instance for each error message, otherwise you are modifying the same object. just adding the same reference (pointer) to the list each time. The referenced object of course contains the last value only then.

  • Adan Member

    When you Add a variable based on a class to a list, you are not making a copy as is the case with simple variables. You simply add its address in memory to the list. By default, if you Add the same variable 20 times, you are simply having a list of 20 pointers that point to the same block of memory.

    When you make a change to globals.MyErrMsgs, you are changing that single block of memory (called an instance in object terminology) and it reflects in the 20 entries in your list, because they all point to the same block of memory.

    You thus need to create a new object for each of your error message:

    ErrorMsgs MyErrMsgs;
    
    MyErrMsgs = new ErrorMsgs();
    case "error_messages": // Error Messages
    MyErrMsgs.companyId = row.ItemArray[0].ToString().Trim().ToLower();
    MyErrMsgs.errMsgId = row.ItemArray[1].ToString().Trim().ToLower();
    MyErrMsgs.description1 = row.ItemArray[2].ToString().Trim();
    MyErrMsgs.description2 = row.ItemArray[3].ToString().Trim();
    MyErrMsgsList.Add(globals.MyErrMsgs);
    MyErrMsgsList.Add(MyErrMsgs);
    

    MyErrMsg should not be defined either as static or into the globals. MyErrMsgsList plays that role.

    Notice that I have moved MyErrMsgs out of the globals. Simply define it in the method where you use it, being sure to instantiate it to a new object (call new on the variable) for each new message.

    Each “new” creates a completely new object, pointing to a new block of memory, independent from the previous one. But if you’ve added that previous one to the list, the framework will keep it alive as long as the list itself lives. You’ve just used one variable to create 20 objects in memory.

  • Abhey Member

    There are two distinct sorts of variables, reference types and value types. Reference types are eg. classes which are reused. Value types are simple variables (eg. int, bool, string) and structures, these are not reused. Assigning a different value to a class means the original variable is modified – even if you have added it to some collection elsewhere.

    You need to understand this behavior not just to solve this problem but to help you in making code that functions as you want in future.

Viewing 3 reply threads
  • You must be logged in to reply to this topic.