Miguel Moura
Miguel Moura

Reputation: 39354

C# forcing to include optional parameters?

I have the following method from Microsoft:

public static string GetPathByAction(this LinkGenerator generator, 
   HttpContext httpContext, 
   string action = null, 
   string controller = null, 
   object values = null, 
   PathString? pathBase = null, 
   FragmentString fragment = default(FragmentString), 
   LinkOptions options = null);

When I call this method without the last parameter I get the error:

  An expression tree may not contain a call or invocation that uses optional arguments

If a parameter is option why do I get such an error?

LinkGenerator is this class:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.routing.linkgenerator?view=aspnetcore-2.2

Update

I am injecting LinkGenerator in a class as follows (I am not getting an error with this code because I am passing all parameters):

public class RequestHandler : IRequestHandler<Request, Response>> {

  private LinkGenerator _linkGenerator;

  public RequestHandler(LinkGenerator linkGenerator) {

    _linkGenerator = linkGenerator;

  } 

  public async Task<Response> Handle(Request request, CancellationToken cancellationToken) {

    List<File> files = getFiles();    

    // WORKS
    var url = _linkGenerator.GetUriByAction(action: "GetByUserId", controller: "FileController", null, "", new HostString());

    // DOES NOT WORK
    var = await files
      .Select(x => new Response {
        Id = x.File.Id,
        Url = _linkGenerator.GetUriByAction(action: "GetByUserId", controller: "FileController", null, "", new HostString())
      }).ToListAsync();

    // Remaining code 

  }

}

public class File { 
  public Int32 Id { get; set; }
  public String Url { get; set; }
}

Upvotes: 0

Views: 3989

Answers (2)

SomethingSImple
SomethingSImple

Reputation: 109

See also: An expression tree may not contain a call or invocation that uses optional arguments

The simple answer is its not that calling the method without the optional parameter that is causing an error but how you're calling. If you're calling the method within a lambda it will only work if you specify the optional parameters.

Upvotes: 0

Related Questions