Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with modifying objects within collections 1

Status
Not open for further replies.

azzazzello

Technical User
Jan 25, 2005
297
US
Greetings,

I have the following code:

Code:
using System;
using System.Collections.Generic;
using System.Text;


class Class1
{
    static void Main()
    {
        dataContainer cont = new dataContainer(1,1);
        Console.WriteLine("set COUNT: {0}, PRICE: {1}",cont.getCount(),cont.getPrice());
        SortedList<string,dataContainer> myList = new SortedList<string,dataContainer>();
        myList.Add("KEY",cont);
        Console.WriteLine("current COUNT: {0}, PRICE: {1}",myList["KEY"].getCount(),myList["KEY"].getPrice());
        myList["KEY"].addCountPrice(10,10);
        Console.WriteLine("updated?? COUNT: {0}, PRICE: {1}",myList["KEY"].getCount(),myList["KEY"].getPrice());
    }

    private struct dataContainer
    {
        private int count;
        private double price;

        public dataContainer(int init_count, double init_price)
        {
            this.count = init_count;
            this.price = init_price;
        }

        public void addCount(int inc_count)
        { this.count += inc_count; }
        public void addPrice(double inc_price)
        { this.price += inc_price; }
        public void addCountPrice(int inc_count, double inc_price)
        {
            this.count += inc_count;
            this.price += inc_price;
        }
        public int getCount()
        { return this.count; }
        public double getPrice()
        { return this.price; }

    }
}

I hope my intent here is clear - I want to modify the object sitting in the myList sorted list. However, the darn thing seems to be returning me a copy of the object rather than a pointer to the actual thing, judging from the fact that the final line of this code prints out 1 instead of 11 for the price and count of the object. I know that I can get the values, construct the new object, and save it over old one, but that set of operations is infinitely more expensive cpu-cycle-wise than simply incrementing the values. Can someone please help me with this? I find it hard to believe that objects in collections are read-only.
 
structs are value types and you'll always get a copy unless you declare it as ref in in the method.

or you could make it more c#y and declare a class rather than a struct.

mr s. <;)

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top