Search code examples
c#azure-cosmosdb

Sending params dynamic[] values to method


In the app I'm working on, a former developer created a method that expects params dynamic[] parameters. I'm familiar with dynamic but not sure how to send parameters to this function.

The method I'm trying to call looks like this:

public async Task CallDbStoredProcedure(string procedureId, string collectionName, params dynamic[] spParameters)
{
   // Makes stored procedure call to Cosmos Db
}

I assume he used dynamic because each parameter can be of different type which is the case in my particular scenario.

I need to send two parameters:

  • @itemId which is a Guid value
  • @statusId which is an int value

How do I create this params dynamic[] with my parameter values so that I can send it to the CallDbStoredProcedure() method?


Solution

  • You don't need to create anything: params parameters arrays are created implicitly by the compiler:

    Guid  itemId   = new Guid( "5fb75eac-9f0b-550c-339f-fc21fde966cd" );
    Int32 statusId = 123;
    
    await CallDbStoredProcedure( procedureId: "PerformPhilately", collectionName: "my stamp collection", itemId, statusId );
    

    But if you really wanted to, you can also do this:

    dynamic[] arr = new dynamic[] { itemId, statusId };
    
    await CallDbStoredProcedure( procedureId: "PerformPhilately", collectionName: "my stamp collection", spParameters: arr );
    

    ...but this is generally inadvisable because with params arrays, the callee method generally assumes ownership of the array (and so can mutate it) whereas if the caller has a named reference to it (especially in an async call-site), they could do a rug-pull.