Linking classes with required datatypes for type safety in C#

Viewed 13

Context

I have been putting together a system that runs multiple jobs, each with their own required data which has been supplied so far in the form of a Dictionary<string, object> which the job can then extract and parse at runtime which offers no real type guarantees when unboxing. This function is provided by the BaseJob class that all jobs inherit from.

There are two parts of this system that I am trying to add some typing guarantees to:

//Scheduling a new job of type MyJob to run
var jobData = new MyJobData { IsDebug = true };
AddJob<MyJob>(schedule, jobData);

and

//Fetching info from the jobData, within the MyJob's Execute function
var isDebug = this.GetJobData<boolean>("IsDebug");

The way I have approached this so far (which I know doesn't work) is:

  1. Create a data storage class with generics public class RequiredData<T> where T : BaseJob
  2. For each job class create a class to hold the required data e.g. MyJob -> MyJobData
  3. These then extend the required data as such public class MyJobData : RequiredData<MyJob>

With this, I can get the type guarantees around AddJob with the following definition

public static void AddJob<TJob>(Schedule schedule, RequiredData<TJob> jobData)

so now the following will fail to compile

var badJobData = new OtherJobData { SomeProperty = false };
AddJob<MyJob>(schedule, badJobData);
//Error: Cannot convert from type OtherJobData to RequiredData<MyJob>

Issue

However, this approach doesn't help the GetJobData definition at all which results in the following clunky usage

//Definition of function (using KeyOf from Apparatus.AOT.Reflection)
public TReturn GetJobData<TReturn, TJob, TJobData>(KeyOf<TJobData> key) where TJob : BaseJob

//Usage in job code
var isDebug = this.GetJobData<boolean, MyJob, MyJobData>("IsDebug");

I expect there is a way to simplify this to this.GetJobData<boolean>("IsDebug") since TJob is just the type of the current class and TJobData is fixed for the current class type (MyJob -> MyJobData, OtherJob -> OtherJobData). Additionally, is there any way to ensure that TReturn matches the type in MyJobData associated with the given string (IsDebug)?

0 Answers
Related