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?

2

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, Factory pattern to the rescue :) ... nice alternative.
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);

2 Comments

you forgot generic arguments on the first Flow (flow's type) ;)
@Sehnsucht Thanks. Fixed
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.

2 Comments

you forgot generic arguments on the first Flow (flow's type) ;)
Thanks :) ... I fixed that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.