Skip to content

Instantly share code, notes, and snippets.

@Virtlink
Last active December 28, 2015 06:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Virtlink/7457611 to your computer and use it in GitHub Desktop.
Save Virtlink/7457611 to your computer and use it in GitHub Desktop.
Copies an array with rank 1 and any lower-bound into a single-dimensional zero-based array (SZ-array) with lower bound zero.
using System;
namespace Virtlink
{
/// <summary>
/// Helper methods for arrays.
/// </summary>
/// <example>
/// Usage example:
/// <code>
/// // Creating an array string[2..11].
/// Array customArray = Array.CreateInstance(typeof(string), new int[] { 10 }, new int[] { 2 });
///
/// // Turn it into a normal array string[10].
/// string[] normalArray = ArrayHelper.ToSZArray&lt;string&gt;(customArray);
/// </code>
/// </example>
/// <remarks>
/// Created by Virtlink. Original source code on GitHub:
/// <see href="https://gist.github.com/Virtlink/7457611"/>.
/// </remarks>
public static class ArrayHelper
{
/// <summary>
/// Copies an array with rank 1 and any lower-bound
/// into a single-dimensional zero-based array (SZ-array) with lower bound zero.
/// </summary>
/// <typeparam name="T">The type of elements.</typeparam>
/// <param name="array">The array to copy from.</param>
/// <returns>The resulting SZ-array.</returns>
public static T[] ToSZArray<T>(Array array)
{
#region Contract
if (array == null)
throw new ArgumentNullException("array");
if (array.Rank != 1)
throw new ArgumentException("Expected array with rank 1.", "array");
#endregion
T[] dest = new T[array.Length];
Array.Copy(array, dest, array.Length);
return dest;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment