13

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 ?

Ehsan88
  • 3,569
  • 5
  • 29
  • 52

5 Answers5

25

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"] }
Martin Booth
  • 8,485
  • 31
  • 31
7

You can also write in one line with array initializer:

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

Check this out: All possible C# array initialization syntaxes

Community
  • 1
  • 1
Olexander Ivanitskyi
  • 2,202
  • 17
  • 32
2
timeslots.PrimaryKey = new DataColumn[] { timeslots.Columns["time"] };
Damith
  • 62,401
  • 13
  • 102
  • 153
1

Drawing on the answers above, I created this extension method which is very helpful and saves me a lot of typing.

/// <summary>
/// Convert the provided object into an array 
/// with the object as its single item.
/// </summary>
/// <typeparam name="T">The type of the object that will 
/// be provided and contained in the returned array.</typeparam>
/// <param name="withSingleItem">The item which will be 
/// contained in the return array as its single item.</param>
/// <returns>An array with <paramref name="withSingleItem"/> 
/// as its single item.</returns>
public static T[] ToArray<T>(this T withSingleItem) => new[] { withSingleItem };
rory.ap
  • 34,009
  • 10
  • 83
  • 174
0

I liked @rory.ap's extension method answer, but I refactored it to have simpler comments and also to handle nulls better.

/// <summary>
/// Creates an array with an object as its single item, or an empty array if the object is null.
/// </summary>
public static T[] ToArray<T>(this T? withSingleItem) =>
   withSingleItem == null ? Array.Empty<T>() : new[] { withSingleItem };
Patrick Szalapski
  • 8,738
  • 11
  • 67
  • 129