14

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 ?

5 Answers 5

27

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"] }
0
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

2
timeslots.PrimaryKey = new DataColumn[] { timeslots.Columns["time"] };
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 };
1

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 };
1
  • 1
    It would be nice if the .NET team would add a Array.One<T>(T value) method. I'd prefer that to polluting my intellisense with more indiscriminate extension methods. Having said that, which is better? "item.ToArray()", "Array.One(item)", or "new[]{item}"? Just realised that in C# 12 we can now just use "[item]" to create an array from an item.
    – Graeme Job
    Nov 15, 2023 at 10:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.