Created
September 21, 2012 16:18
-
-
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.
This file contains hidden or 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
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