0

In a dynamic way, I'm looking to set the .Value property of the SyncVar property of the Unit class. The following won't compile and I don't want to hardcode SynvVar<int> because it could be a number of base types <int>, <string>, <bool>, etc.

class SyncVar<T>
    {
        public T Value { get; set; }
    }

    class Unit
    {
        public SyncVar<int> Health { get; set; } = new SyncVar<int>();
    }

    class Program
    {
        static void Main(string[] args)
        {
            Unit unit = new Unit();
            unit.Health.Value = 100;

            var prop = unit.GetType().GetProperty("Health").GetValue(unit);

            // compile error as prop object doesn't contain .Value
            // I need to dynamically figure out what type was used in this generic property so I can cast to that and set it's value
            prop.Value = 50;
        }
    }
user441521
  • 6,942
  • 23
  • 88
  • 160

1 Answers1

1

In case of arbitrary T you can try Reflection one time more:

      prop.GetType().GetProperty("Value").SetValue(prop, 50);
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215