0

I have an Entity abstract generic class which main characteristic is that it can be grouped with other instances of different implementations of this same class, around a common "group id".

For example, a MoveBehaviour and FlyBehaviour can implement Entity so two given instances of these classes could be assigned to a given Person instance and FlyBehaviour could look up its corresponding MoveBehaviour easily.

One can argument I'm killing OOP so I should go home and never ever touch a computer again, but let's have this discussion some other day.

This is my attempt:

public abstract class Entity<T> where T : Entity<T>
{
    private int groupId;
    protected static Dictionary<int, T> entityMap = new Dictionary<int, T>();

    public Entity(int groupId)
    {
        this.groupId = groupId;
        entityMap.Add(groupId, (T) this);
    }

    public T2 GetCoEntity<T2>() where T2 : Entity<T2>
    {
        return T2.entityMap[groupId];
    }
}

The compiler complains it doesn't know what entityMap is and I don't understand why.

Roberto
  • 11,557
  • 16
  • 54
  • 68
  • did you try with return entityMap[groupId]; instead of return T2.entityMap[groupId]; – Mukul Keshari Oct 30 '19 at 00:01
  • but that would return an instance of `T`, not `T2`, right? – Roberto Oct 30 '19 at 00:05
  • `T2.entityMap` trying to access protected member of another type, which is not allowed. Even `T2` derives from `Entity` it still considered as separate class and you are not able access it's protected members. – Fabio Oct 30 '19 at 00:16
  • 1
    @Fabio It doesn't work if it's public too. And `entityMap` is a member of their base type. – Roberto Oct 30 '19 at 00:20
  • Are you sure this would be correct signature `public int GetCoEntity() where int : Entity`? – Fabio Oct 30 '19 at 00:21
  • @StephenKennedy The OP is trying to access the static member, thus does not need an instance. – juharr Oct 30 '19 at 00:22
  • @StephenKennedy Doesn't have to be `public` just has to use `Entity` since `T2` is just a generic type and you need the actual class type to access static member. – juharr Oct 30 '19 at 00:25
  • @Fabio `int` cannot be the generic type because it does not implement `Entity` this only works for classes like `public class MyClass : Entity` – juharr Oct 30 '19 at 00:26

1 Answers1

3

You need to add the class type to the call:

return Entity<T2>.entityMap[groupId];

EDIT

Why is this needed?

Static methods/properties are not virtual so the entityMap object does not exist on T2 as it is derived from Entity<T2>. You need to use the base type when using the static property

Simply Ged
  • 8,250
  • 11
  • 32
  • 40
  • Why? Isn't `T2` `Entity`?? – Roberto Oct 30 '19 at 00:08
  • @Roberto I had to get my head around this but I've updated the answer - there are other references about static methods and properties but I've added the one I think is relevant. Feel free to point out a better one if you find one :-) – Simply Ged Oct 30 '19 at 00:27