Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an object to a single item array of object (C#)

Tags:

arrays

c#

Some functions only accept arrays as arguments but you want to assign a single object to them. For example to assign a primary key column for a DataTable I do this:

DataColumn[] time = new DataColumn[1];
time[0] = timeslots.Columns["time"];
timeslots.PrimaryKey = time;

This seems cumbersome, so basically I only need to convert a DataColumn to a DataColumn[1] array. Is there any easier way to do that ?

like image 680
Ehsan88 Avatar asked Sep 19 '13 03:09

Ehsan88


1 Answers

You can write it using the array initializer syntax:

timeslots.PrimaryKey = new[] { timeslots.Columns["time"] }

This uses type inference to infer the type of the array and creates an array of whatever type timeslots.Columns["time"] returns.

If you would prefer the array to be a different type (e.g. a supertype) you can make that explicit too

timeslots.PrimaryKey = new DataColumn[] { timeslots.Columns["time"] }
like image 157
Martin Booth Avatar answered Sep 18 '22 18:09

Martin Booth