Skip to content

Instantly share code, notes, and snippets.

@amogram
Last active December 15, 2015 10:19
Show Gist options
  • Save amogram/5244719 to your computer and use it in GitHub Desktop.
Save amogram/5244719 to your computer and use it in GitHub Desktop.
Safe Casting ToList<T>() in C#
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;
}
}
@amogram
Copy link
Author

amogram commented Nov 27, 2013

Gave LengthOrNull a nicer name.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment