0

I'm trying to create a simulator using characters, and I use many generics to work with their properties regardless of their exact type (weight, length, time, etc). This way, I can still compare them or generate them randomly.

In a certain class, I want to link each character property with a distribution method (for example, link the age with a normal distribution), regardless of the type. Both the character properties and the distribution method use generics, so I used as a type. In the dictionnary below, I just want the property and the distribution method to have the same type.

public Dictionary<CharacterProperty<object>, PropertyDistributor<object>> properties = new Dictionary<CharacterProperty<object>, PropertyDistributor<object>>();

//example
properties.Add(new CharacterProperty<Time>(
        c => c.age,
        (c, v) => c.age = v
    ), new NormalDistribution<Time>(20 * Time.Y, 35 * Time.Y)
);

Here is an example of a method using this dictionnary to generate a character. I create a empty character then generate each of the properties using a distribution method. I don't use types in this method because the distribution method returns an object of the type of the property.

Character c = new Character();
foreach(KeyValuePair<CharacterProperty<object>, PropertyDistributor<object>> v in repartitor.properties)
    v.Key.set(c, v.Value.generate());
return c;

Though I don't get any error in the function above, I get one when I try to add an element to my dictionnary.

Impossible cast from CharacterProperty<Time> to CharacterProperty<object>

Why is this cast impossible ? How should I do to avoid this error ?

F. Morival
  • 331
  • 1
  • 2
  • 9
  • You can't. https://stackoverflow.com/questions/19077122/generic-class-covariance *C# 4 and above support covariance and contravariance of generic interfaces and generic delegates when they are constructed with reference types*. So no covariance/contravariance for `class`es. – xanatos May 21 '18 at 13:18
  • 4
    Just because `Time` is an `object` it doesn't mean that `CharacterProperty – Enigmativity May 21 '18 at 13:21
  • What should I do then ? I don't want to create a list for each of my types. – F. Morival May 21 '18 at 13:24
  • @F.Morival - Internally use a `Dictionary` and externally use generic methods and reflection to access the elements of the dictionary. Or perhaps `Dictionary` and use generic methods... – Enigmativity May 21 '18 at 13:26

0 Answers0