Last active
December 15, 2015 10:19
-
-
Save amogram/5244719 to your computer and use it in GitHub Desktop.
Safe Casting ToList<T>() in C#
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
public static class SafeExtensions | |
{ | |
public static IEnumerable<T> SafeToList<T>(this IEnumerable<T> source) | |
{ | |
return source != null ? source.ToList() : null; | |
} | |
public static T[] SafeToArray<T>(this IEnumerable<T> source) | |
{ | |
return source != null ? source.ToArray() : null; | |
} | |
// Returns length of array if not null, otherwise zero. | |
public static int LengthOrNull<T>(this T[] source) | |
{ | |
return source != null ? source.Length : 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Gave LengthOrNull a nicer name.