Search code examples
c#genericsgeneric-programming

Generic List/Dictionary based on Property/Parameter


For starters, I have implemented a workaround to this question based on having multiple private variables store information, and get/set on the affected object.

The scope of this questions is for learning/reference.

Scenario: I have an interface that manages multiple objects (2 in this example).

interface Imoon
??? SomePropertyName {get;set;}

class Foo : Imoon
public TypeA SomePropertyName {get;set;}
public enumMyType TypeStorage {get;set}

class Bar : Imoon
public TypeB SomePropertyName {get;set;}
public enumMyType TypeStorage {get;set;}

The goal is to be able to reference a list/dictionary/array of objects that may change in type (similiar to a generic). The types don't impact the logic, they are partitioned into separate handlers and managed there.

  • Once declared, the type of the object does not change.

  • The Type is the same for all elements within the Enumerable, however may change between different objects.

Example declarations:

Dictionary<string,TypeA> myDictionary;
Dictionary<string,TypeB> myDictionary;

or as a list:

class Foo

List<TypeA> myValues
List<string> myKeys

class Bar

List<TypeB> myValues
List<string> myKeys

If anyone has any suggestions on how to implement this, or suggestions for improvement please let me know :)


Solution

  • For Archiving, I was able to reach the desired result by using a Generic interface as Recommended by johnny5 above. I've included a example of the solution, and how to implement it with a given type (TypeA), and it could be done on TypeB aswell.

    public interface ICollection<T>
    {
        Dictionary<string,T> TypeDictionary { get; set; }
        void AddToDictionary(Dictionary<string,T> Addition
        int FileCount { get; }
    }
    
    public class TypeACollection : ICollection<TypeA>
    {
        private Dictionary<string,TypeA> myTypeDictionary = new Dictionary<string, TypeA>();
        public void AddToDictionary(Dictionary<string, TypeA> Addition)
        {
            foreach (var keyValuePair in Addition)
            {
                TypeDictionary[keyValuePair.Key] = keyValuePair.Value;
            }
        }
        public Dictionary<string, TypeA> GetTypeDictionary()
        {
            return TypeDictionary;
        }
    
        private void ClearDictionary()
        {
            TypeDictionary.Clear();
        }
    
        public Dictionary<string, TypeA> TypeDictionary { 
             get {   return myTypeDictionary; } 
             set {   myTypeDictionary = value; } 
        }
    
        public int FileCount {get { return TypeDictionary.Keys.Count; }}
    }
    public class TypeA { }
    public class TypeB { }