-2

I'm trying to make a generic Type to handle all my references between C# entities.

  • In one case, a reference is simply an int ID, so the proper data structure to remember where ans entity it is been used, would be HashSet<int>
  • In other scenario, An entity could be used in tree structure, so I need to remember both int Id and path which is a collection of objects. The proper data structure would a Dictionary<int, Tvalue>

Here is What I have so far:

public class References<TValue> : Dictionary<int, TValue>
{
}

public class References : HashSet<int>
{
}

public class MyEntityWithDefaultReferences
{
    public References References;
}

public class MyEntityWithPathReferences<PathType>
{
     public References<PathType> References;
}

Is there a way to make second References class inherit from the first one? So I can use parent class every where.

Mhd
  • 2,778
  • 5
  • 22
  • 59
  • c# doesn't have multiple inheritance. you could use multiple interfaces. – Daniel A. White Mar 25 '19 at 15:43
  • 2
    https://stackoverflow.com/questions/21692193/why-not-inherit-from-listt/21694054 This applies to `HashSet` and `Dictionary` as well. – Daniel Mann Mar 25 '19 at 15:45
  • Maybe you can use a [KeyedCollection](https://learn.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.keyedcollection-2?view=netframework-4.7.2)? – Magnetron Mar 25 '19 at 15:57
  • @Magnetron I can't see How can I use KeyedCollection if I need only the key – Mhd Mar 25 '19 at 16:01
  • @Mhd let me see if I understood correctly, you have two classes, one is just an id, the other is id + a value and you want to store them both in the same Collection? – Magnetron Mar 25 '19 at 16:11
  • @Magnetron Actually, I need a collection that could store keys in one scenario. In another scenario, keys and values. – Mhd Mar 25 '19 at 16:21
  • Don't use inheritance for composition. – NetMage Mar 25 '19 at 21:46

1 Answers1

0

Well, how about this way

public interface MyReference{
    int Id{get;set;}
}

public class SimpleReference : MyReference
{
    public int Id{get;set;}
}
public class CompoundReference<T> : MyReference
{
    public int Id{get;set;}
    public T TValue{get;set;}
}

public class ReferenceCollection : KeyedCollection<int, MyReference>
{
    protected override int GetKeyForItem(MyReference item)
    {
        return item.Id;
    }
}

And you can use like

SimpleReference sr = new SimpleReference(){Id=1};
CompoundReference<string> cr = new CompoundReference<string>(){Id=2,TValue="Test"};

ReferenceCollection col = new ReferenceCollection();
col.Add(sr);
col.Add(cr);
Console.WriteLine(col.Contains(1)); //true
Console.WriteLine(col.Contains(2)); //true
Console.WriteLine(col.Contains(3)); //false
var i1 = col[1]; //returns sr
var i2 = col[2]; //return cr
Magnetron
  • 7,495
  • 1
  • 25
  • 41