4

Is it possible to "spread" array elements in c# so that I can pass them to another function?

For example, in Javascript, we can do

function myFunction(x, y, z) { }
var args = [0, 1, 2];
myFunction(...args);

Is there a similar functionality in c#? The reason I want to do this is that I have a SQL statement with a lot of columns and I want to instantiate a new object with each row without having to explicitly set each field to a particular column. I can use reader.GetValues to get an array of all my column values, but can I use this to conveniently create objects?

Simon
  • 1,681
  • 1
  • 21
  • 34
  • 1
    With C# 6 or newer with it's new ValueTuples you can. However I would reccomend switching to a lightweight ORM like [Dapper](https://github.com/StackExchange/Dapper) (it is the library that stack overflow uses to run it's own website) – Scott Chamberlain Sep 05 '17 at 18:39
  • 1
    You might also want to look at the [`params`](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params) keyword that allows you to pass an array or a set of separate variables/constants. Though that's some that has to be part of the method definition and all the values would have to be the same type. – juharr Sep 05 '17 at 18:41
  • 1
    Also for mapping SQL to objects you might want to look at [`Dapper`](https://github.com/StackExchange/Dapper). It simplifies a lot of ADO.Net code to allow you map the results to objects. – juharr Sep 05 '17 at 18:43
  • If that doesn't answer your question, [edit] to explain why `params` won't work. –  Sep 05 '17 at 18:44

0 Answers0