0

I have the following:

public class Query : IAsyncRequest<Envelope<Reply>> { }

public class Reply { }

public class Flow<TQuery, TReply> where TQuery: IAsyncRequest<Envelope<TReply>>, IRequest<Envelope<TReply>> {

  public TQuery Query { get; set; }
  public TReply Reply { get; set; }

  public Flow(TQuery query, TReply reply) {
    Query = query;
    Reply = reply;
  }
}

When I try to create an instance of Flow as

Query query = service.GetQuery();
Reply reply = service.GetReply();
Flow flow = new Flow(query, reply);

I get the error:

Using the generic type 'Flow<TQuery, TReply>' requires 2 type arguments 

Can't I create a Flow this way?

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481

3 Answers3

2

No you can't, as said in @NineBerry's answer, the syntax new type must be the "real" type with mandatory generics arguments so you must write :

Flow<Query, Reply> flow = new Flow<Query, Reply> (query, reply);

That said, that constraint doesn't apply to a method, so you could write a static method to do the job :

static class Flow // not generic (same name isn't mandatory)
{
    public static Flow<TQuery, TReply> Create (TQuery query, TReply, reply) where /* constraint */
    {
        return new Flow<TQuery, TReply> (query, reply);
    }
}

// usage
Flow<Query, Reply> flow = Flow.Create (query, reply);
// or with var
var flow = Flow.Create (query, reply);
Community
  • 1
  • 1
Sehnsucht
  • 5,019
  • 17
  • 27
1

You need to specify the types explicitly. Type inference is not supported here. See also Why can't the C# constructor infer type?

Query query = service.GetQuery();
Reply reply = service.GetReply();
var flow = new Flow<Query, Reply>(query, reply);
Community
  • 1
  • 1
NineBerry
  • 26,306
  • 3
  • 62
  • 93
0

No, you have to define the types you want to use:

Flow<Query, Reply> flow = new Flow<Query, Reply>(query, reply);

C# constructors do not support type inference.

Bernhard Koenig
  • 1,342
  • 13
  • 23