Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9096431
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T23:51:02+00:00 2026-06-16T23:51:02+00:00

I couldn’t find a complete example of how to properly encapsulate a Dictionary. All

  • 0

I couldn’t find a complete example of how to properly encapsulate a Dictionary. All I needed/wanted to do was ‘override’ the Add method which I know can’t be overridden because it is not virtual. Based on some research I found I needed to encapsulate it using a private Dictionary and implementing the IDictionary Interface.

The most complete example I could find was here, which I mostly copy-pasted and guessed about the things that didn’t match (the example implements a read-only dictionary, whereas I want full default functionality with a customized Add() method).

Full Compilable Code below:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

namespace IDictionary
{
    class Program
    {
        static void Main(string[] args)
        {
            Registers<string, dynamic> DynRegistry = new Registers<string, dynamic>();

            DynRegistry.Add("Foo", 100);
            Console.WriteLine("DynRegistry Size: {0}", DynRegistry.Count);
            foreach (var item in DynRegistry)
            {
                Console.WriteLine("\tName: {0}, Value: {1}", item.Key, item.Value);
            }
            DynRegistry.Add("Foo2", "Hello World");
            Console.WriteLine("DynRegistry Size: {0}", DynRegistry.Count);
            foreach (var item in DynRegistry)
            {
                Console.WriteLine("\tName: {0}, Value: {1}", item.Key, item.Value);
            }
            DynRegistry.Add("Foo", true);
            Console.WriteLine("DynRegistry Size: {0}\r\n", DynRegistry.Count);
            foreach (var item in DynRegistry)
            {
                Console.WriteLine("\tName: {0}, Value: {1}", item.Key, item.Value);
            }
            Console.ReadKey();
        }
    }

    class Registers<TKey, TValue> : IDictionary<TKey, TValue>,  ICollection
    {
        //Fields
        private Dictionary<TKey, TValue> source;
        private object syncRoot;

        //Constructor
                    public Registers()
    {
        this.source = new Dictionary<TKey, TValue>();
    }

        //Wrapped Methods
                                                public void Add(TKey key, TValue value)
    {
        if (this.source.ContainsKey(key))
        {
            this.source[key] = value;
        }
        else
        {
            this.source.Add(key, value);
        }
    }

        //Implement default Interfaces
                        void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
    {
        ICollection<KeyValuePair<TKey, TValue>> collection = this.source;
        collection.CopyTo(array, arrayIndex);
    }
        public int Count { get { return this.source.Count; } }
        public ICollection<TKey> Keys { get { return this.source.Keys; } }
        public ICollection<TValue> Values { get { return this.source.Values; } }
        bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return false; } }
        bool ICollection.IsSynchronized { get { return false; } }
        object ICollection.SyncRoot
    {
        get
        {
            if (this.syncRoot == null)
            {
                ICollection collection = this.source as ICollection;

                if (collection != null)
                {
                    this.syncRoot = collection.SyncRoot;
                }
                else
                {
                    Interlocked.CompareExchange(ref this.syncRoot, new object(), null);
                }
            }
            return this.syncRoot;
        }
    }
        public TValue this[TKey key]
    {
        get { return this.source[key]; }
        set { this.source[key] = value; }
    }
        public bool ContainsKey(TKey key) { return this.source.ContainsKey(key); }
        public bool Remove(TKey key) { return this.source.Remove(key); }
        public bool TryGetValue(TKey key, out TValue value) { return this.source.TryGetValue(key, out value); }
        void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
    {
        ICollection<KeyValuePair<TKey, TValue>> collection = this.source;
        collection.Add(item);
    }
        void ICollection<KeyValuePair<TKey, TValue>>.Clear()
    {
        ICollection<KeyValuePair<TKey, TValue>> collection = this.source;
        collection.Clear();
    }
        bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
    {
        ICollection<KeyValuePair<TKey, TValue>> collection = this.source;
        return collection.Contains(item);
    }
        bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
    {
        ICollection<KeyValuePair<TKey, TValue>> collection = this.source;
        return collection.Remove(item);
    }
        void ICollection.CopyTo(Array array, int index)
    {
        ICollection collection = new List<KeyValuePair<TKey, TValue>>(this.source);
        collection.CopyTo(array, index);
    }
        IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
    {
        IEnumerable<KeyValuePair<TKey, TValue>> enumerator = this.source;
        return enumerator.GetEnumerator();
    }
        IEnumerator IEnumerable.GetEnumerator()
    {
        return this.source.GetEnumerator();
    }
    }
}

Two reasons I am posting this:

  1. So that anyone else that needs to do this doesn’t have to spend 30 minutes re-typing redundant code.
  2. Feedback about whether I did this all correctly. I was confused as to if/why I needed to implement the ICollection interface (ie. Does a normal Dictionary do this or would the IDictionary have the complete complement of Dictionary features without the need for ICollection).

All I really needed was a normal Dictionary with an Add method that does AddOrReplace() instead of Add (or crash because the Key already exists). The work required to achieve this seemed to be a bit of overkill.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T23:51:03+00:00Added an answer on June 16, 2026 at 11:51 pm

    You can use

    dict[key]=value
    

    for add or replace if that is all you want. So no need to wrap a dictionary.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Couldn't find this on stackoverflow and I did have an example of it which
I couldn't find any question similar to this one, I wanted to know about
Couldn't find a method like the int executeUpdate(String sql, int autoGeneratedKeys) in php. I
Couldn't really find it, but probably it's me not knowing how to search properly
i couldn't find anything so i just wanted to take a url and then
Couldn't find anything about this on the internet, or stackoverflow?!? Basic Example: A great
Couldn't find any related resources I want to add a custom property to my
I couldn't find the exact number of current Active Template Library (ATL) which distribute
Couldn't find an answer to this anywhere, but essentially I am wanting to add
Couldn't comment on this post, which states the problem I'm experiencing: jQuery remove() on

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.