Last active
December 28, 2015 06:29
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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<string>(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