Miguel Moura
Miguel Moura

Reputation: 39484

Create instance of object with Generics

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?

Upvotes: 0

Views: 71

Answers (3)

NineBerry
NineBerry

Reputation: 28539

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);

Upvotes: 1

Bernhard Koenig
Bernhard Koenig

Reputation: 1382

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.

Upvotes: 0

Sehnsucht
Sehnsucht

Reputation: 5049

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);

Upvotes: 2

Related Questions