Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to copy dictionary returned by function

Tags:

c#

dictionary

I´m using C# and have the following function:

public static Dictionary<string, string> GetData(string fileName)
{
     Dictionary<string, string> returnDictionary = new Dictionary<string,string>();

     .... Load data from file into dictionary........

     return returnDictionary;
}

What is the correct way to use the returned dictionary:

public class WhateverClass
{
     Dictionary <string, string> classDictionary = new Dictionary<string,string>();

     ... Class code....

     public void WhateverFunction ()
     { 
           ...

           // SHALL I USE

           classDictionary = GetData(filename);

           ...

           // OR
           classDictionary = new Dictionary<string,string>(GetData(filename));
     }
}

What should be the proper use of the returned dictionary, copying it to an already created dictionary in my class.

like image 458
Mendes Avatar asked Jun 27 '26 06:06

Mendes


2 Answers

I would consider getting rid of your class level variable based upon the usage. Scope the dictionary correctly.

If you are going to be continuously writing over your class dictionary within different method calls, then it probably should not be a class level variable.

As for generating the dictionary, there is no need to call classDictionary = new Dictionary<string,string>(GetData(filename)); because your method already creates a new dictionary. Essentially you're creating a new dictionary then copying it and throwing away what you made.

Just use classDictionary = GetData(filename);

like image 145
Daniel Avatar answered Jun 29 '26 21:06

Daniel


You don't need to reconstruct the dictionary, the existing reference will be more than sufficient.

C# uses a reference-count based garbage collector. By returning (and assigning the return value) the dictionary, you add to the reference count. Until that reference (and all other references) go out of scope, you can use the dictionary with no worries.

Of course, without a reference it would be hard to use the dictionary in the first place :).

Very rarely do you actually need to perform a deep copy, and the code you posted doesn't seem to warrant it here.

like image 25
BradleyDotNET Avatar answered Jun 29 '26 20:06

BradleyDotNET