Thread: Dictionary Values copy

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    1,579

    Dictionary Values copy

    Hello everyone,


    Here is my code to make a duplicate value copy of all the Values in a dictionary instance -- not just reference. So, I use CopyTo method.

    My current issue is, I think my code is stupid but do not know how to solve it. My specific concern is,

    1.

    the code Foo[] FooArray = new Foo[3] creates 3 new instances of Foo, the code dic.Values.CopyTo(FooArray, 0) will overwrite the 3 new instances of Foo? So, seems it is stupid to create 3 new instances of Foo in Foo[] FooArray = new Foo[3], but never use them and overwrite them? Any ideas? Is it an issue?

    2.

    Maybe I am wrong, the code Foo[] FooArray = new Foo[3] creates only references variable of Foo class? Not class instances variable themselves?

    Code:
        class Foo
        {
            public int abc;
    
            public Foo (int i)
            {
                abc = i;
            }
            
        }
        
        public static void Main()
        {
    
            Dictionary<int, Foo> dic = new Dictionary<int,Foo>();
            dic.Add(1, new Foo(10));
            dic.Add(1, new Foo(20));
            dic.Add(3, new Foo(30));
    
            Foo[] FooArray = new Foo[3];
    
            dic.Values.CopyTo(FooArray, 0);
    
            return;
        }

    thanks in advance,
    George

  2. #2
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    the code Foo[] FooArray = new Foo[3] creates 3 new instances of Foo
    No, it creates 3 pointers (references or whatever u like to call em), it doesn't actually create the objects.
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. disposing error
    By dropper166 in forum C# Programming
    Replies: 2
    Last Post: 03-30-2009, 11:53 PM
  2. putting values into an array
    By zdream8 in forum C Programming
    Replies: 15
    Last Post: 05-21-2008, 11:18 PM
  3. Replies: 1
    Last Post: 12-30-2007, 10:08 AM
  4. spell check in C using a dictionary file
    By goron350 in forum C Programming
    Replies: 10
    Last Post: 11-25-2004, 06:44 PM
  5. Copy Constructor crashing program
    By bob2509 in forum C++ Programming
    Replies: 5
    Last Post: 11-12-2002, 04:21 PM