0

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;
            }
        }
Servy
  • 202,030
  • 26
  • 332
  • 449
dnf
  • 1,659
  • 2
  • 16
  • 29
  • 2
    Please share your code. The default value for a reference type is `null`. I'm not sure what you want to fix. – Dan Wilson Jul 12 '18 at 18:37
  • Why don't you know the _type_ of your return value? – xxbbcc Jul 12 '18 at 18:53
  • To get the default value of a type, you can just use `default(T)` - no need for a function for that. – xxbbcc Jul 12 '18 at 18:56
  • With your updated answer, you should probably use `nameof(GetDefaultTask)` rather than `"GetDefaultTask"`. It just means if the method is renamed it will catch it, if you use a tool to find references to the method it will find it, it won't claim it's an unused method, etc. – George Helyar Jul 12 '18 at 19:31
  • Yes you are right - it is only fast dev :) – dnf Jul 12 '18 at 19:38
  • It's not appropriate to edit an answer into your question. If you want to post an answer to your question, post an answer. – Servy Jul 12 '18 at 19:40

1 Answers1

1

Generics are used for compile time type checking. You can't define a <T> at runtime. The best you could do is Task<object> with a cast to the type you want after awaiting it, or maybe a Task<dynamic>.

I'm not sure why you want to do this.

If you can supply a generic type at compile time, you can just do

public Task<T> GetDefaultTask<T>() {
    return Task.FromResult(default(T));
}
George Helyar
  • 4,319
  • 1
  • 22
  • 20
  • Not exacly what I need but give me an inspiration ;) I will updated my question with answer – dnf Jul 12 '18 at 19:11