Sheen
Sheen

Reputation: 3451

How to swap 2 Dictionary objects without making copy in C#

all:

I have 2 Dictionary objects d1 and d2. They are created separately at beginning, and contents are added to them separately. After some processing, I want to do following things:

I am C# beginner and only find below way to do this job:

d1 = new Dictionary<int, int>(d2);
d2 = new Dictionary<int, int>();

Can I do it more efficiently like C++ way, like below? Pseudo code:

d1 = d2;
d2 = new Dictionary<int, int>();

Thanks.

Upvotes: 0

Views: 1246

Answers (1)

Jason De Oliveira
Jason De Oliveira

Reputation: 1752

d1 = d2;
d2 = new Dictionary<int, int>();

This will in fact do the job. I don't see why this would not work. Dictionaries are reference types, so you won't copy them but just re-assign the reference if you do the above (exactly what you want to do).

http://msdn.microsoft.com/en-us/library/490f96s2.aspx

Upvotes: 3

Related Questions