Skip to content

Instantly share code, notes, and snippets.

@kcargile
Created September 21, 2012 16:18
Show Gist options
  • Save kcargile/3762424 to your computer and use it in GitHub Desktop.
Save kcargile/3762424 to your computer and use it in GitHub Desktop.
.NET Clones a collection in a way that is safe even it if it null.
namespace Extensions
{
/// <summary>
/// Extension methods for classes that implement the <see cref="IEnumerable"/> interface.
/// </summary>
public static class IEnumerableExtensions
{
/// <summary>
/// Clones the list in a way that is safe even it if it null.
/// </summary>
/// <typeparam name="TU">The type of items in the list.</typeparam>
/// <param name="source">The source.</param>
/// <returns>
/// A deep copy of <b>param</b> or null.
/// </returns>
public static IEnumerable<TU> NullSafeClone<TU>(this IEnumerable<TU> source) where TU : class, ICloneable
{
if (null == source)
{
yield break;
}
foreach (TU obj in source)
{
yield return (TU)obj.Clone();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment