Matheus Lima
Matheus Lima

Reputation: 2143

Using an optional parameter in C# as an Object

i have this code:

public IHttpActionResult Get([FromUri]GetFilesRequest request)

If request is null, I want to create a new GetFilesRequest, because in the constructor I did this to create default params of the class:

public GetFilesRequest()
    {
        Sort = "latest";
        Filter = "";
    }

So I'm thinking about:

public IHttpActionResult Get([FromUri]GetFilesRequest request = new GetFilesRequest)

But I'm getting this warning:

'request' is of type 'GetFilesRequest'. A default parameter value of a reference type other than string can only be initialized with null.

Upvotes: 2

Views: 4498

Answers (3)

D Stanley
D Stanley

Reputation: 152501

No - the default value must be a compile-time constant. Can you use an overload instead?

public IHttpActionResult Get()
{
     return Get(new GetFilesRequest());
}

Upvotes: 6

Kami
Kami

Reputation: 19407

As the error indicates this is not possible as a parameter. However you can restructure the code as such

public IHttpActionResult Get([FromUri]GetFilesRequest request = null)
{
   if (request == null) request = new GetFilesRequest();

   // TODO : Remaining method body
}

Upvotes: 2

Darren Kopp
Darren Kopp

Reputation: 77627

You can only use a constant value that the compiler can create. What you have would require a runtime object allocation, so that's why the compiler is complaining. Try something like this.

public IHttpActionResult Get([FromUri]GetFilesRequest request = null) {
    request = request ?? new GetFilesRequest();
}

Upvotes: 4

Related Questions