Re: Dictionary Values copy
Code:
Foo[] FooArray = new Foo[3];
That does not create 3 Foo instances. It only creates an array that has 3 elements set to null. Have you tried to run it in debugger and look at the values?
You could also put a message in the constructor of Foo and see that it's not printed.
Code:
public Foo(int i)
{
abc = i;
Console.WriteLine("Constructs Foo({0})", i);
}
Re: Dictionary Values copy
Thanks cilu,
So this code Foo[] FooArray = new Foo[3] will only create 3 references and make them refer to NULL? Then code dic.Values.CopyTo(FooArray, 0) will create 3 instances of Foo class, and assign the 3 NULL references variables in FooArray to point to the instances?
Quote:
Originally Posted by cilu
Code:
Foo[] FooArray = new Foo[3];
That does not create 3 Foo instances. It only creates an array that has 3 elements set to null. Have you tried to run it in debugger and look at the values?
You could also put a message in the constructor of Foo and see that it's not printed.
Code:
public Foo(int i)
{
abc = i;
Console.WriteLine("Constructs Foo({0})", i);
}
regards,
George
Re: Dictionary Values copy
You know, most of the time, the best way is to try it.
Re: Dictionary Values copy
Thanks cilu!
I have tested CopyTo will only copy the reference, not the references, to my surprise. :-)
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(2, new Foo(20));
dic.Add(3, new Foo(30));
Foo[] FooArray = new Foo[3];
dic.Values.CopyTo(FooArray, 0);
// change the 1st one
FooArray[0].abc = 40;
// output 40
Console.WriteLine(dic[1].abc);
return;
}
Quote:
Originally Posted by cilu
You know, most of the time, the best way is to try it.
regards,
George
Re: Dictionary Values copy
C# works in most cases only with references. For getting duplicates you should implement ICloneable in your business class and call the clone() method for getting a second instance of the object. Thats the usual way in C# as far as I know.
Re: Dictionary Values copy
Quote:
I have tested CopyTo will only copy the reference, not the references, to my surprise. :-)
Hm, Foo is a class right? That makes it a reference type. So of course it behaves as you observed. In .NET there are two kind of types: value types, copied/passed by value and reference types, copied/passed by reference.
Make Foo a struct and then see what happens.