jeudi 12 juillet 2018

How to create Task

Is there any way to create Task<T> in runtime where T is the type known only in runtime? I would like to create Task<T> with default value for T but after obtaining default value for T and use Task.FromResult(default_value) I’m getting Task<object> instead of Task<T> because in most cases default value is null. Any Idea to fix this?

static void Main(string[] args)
        {
            var type = typeof(string); // fin real code type resolved in runtime
            var default_value = GetDefaultValue(type);
            var test = Task.FromResult(default_value); //Task<object> - how to get Task<T>
        }

        public static object GetDefaultValue(Type t)
        {
            if (t.IsValueType)
            {
                return Activator.CreateInstance(t);
            }
            else
            {
                return null;
            }
        }





Aucun commentaire:

Enregistrer un commentaire