codes_occasionally
codes_occasionally

Reputation: 9566

In C# .NET, is there a reason for no copy constructor for StringDictionary?

I apologize if this is a dumb question, but hear me out:

Dictionary<string, string> genericDict = new Dictionary<string, string>;
genericDict.Add("blah", "bloop");
// Use the copy constructor to create a copy of this dictionary
return new Dictionary<string, string>(genericDict);

In the above code sample, I can create a copy of a generic dictionary.

Now suppose I'm using a System.Collections.Specialized.StringDictionary, because I don't feel like typing the "string" types everywhere. StringDictionary has no copy constructor! In fact, it only has the default constructor.

Sure, I can iterate through the StringDictionary and add each key/value pair manually, but I don't want to :-P

Why no copy constructor? Am I missing something here?

Upvotes: 2

Views: 1258

Answers (4)

Randolpho
Randolpho

Reputation: 56391

I agree with the consensus -- you're better off using Dictionary<string, string>. But if you don't like typing the generic types all the time, you could create your own subclass:

public class StringDict : Dictionary<string, string>
{
  // duplicate all Dictionary's constructors here, calling the base constructor for each. 
}

Et Voila! Whenever you want to use a string Dictionary, you use StringDict instead.

Upvotes: 2

Andrew Hare
Andrew Hare

Reputation: 351516

The StringDictionary type is rather obsolete. I think that Dictionary<String,String> is what you want to use here.

The Dictionary<TKey,TValue> type implements some strongly-typed interfaces (ICollection<KeyValuePair<TKey, TValue>> and IEnumerable<KeyValuePair<TKey, TValue>>) which makes it more useful than the StringDictionary type.

While the StringDictionary type is strongly typed I wouldn't advise its use for the sake of laziness alone.

Upvotes: 9

Tadmas
Tadmas

Reputation: 6358

If you don't want to type the "string" types anywhere but are otherwise happy with Dictionary<string,string>, then create a new class that subclasses Dictionary<string,string> and just don't override any methods. You can even call it StringDictionary, as long as it's in a different namespace.

Upvotes: 1

Keltex
Keltex

Reputation: 26426

If you really want to use a StringDictionary (perhaps to support a legacy application), you can create an extension method:

public static StringDictionary NewCopy(this StringDictionary olddict)
{
    var newdict = new StringDictionary();
    foreach (string key in olddict.Keys)
    {
        newdict.Add(key, olddict[key]);
    }
    return newdict;
}

Then you can do this:

StringDictionary newdict = olddict.NewCopy();

Upvotes: 5

Related Questions