I come from the Wild Wild West of PHP and Javascript where you can return anything from a function. While I do hate that lack of accountability, I also face a new challenge in my effort to keep my code "perfect".
I made this generic function to pick a random element from a list
public static T PickRandom<T>(this IList<T> list) {
Random random = new Random();
int rnd = random.Next(list.Count);
return list[rnd];
}
But I want to protect myself from using it on a list with 0 values. Obviously I cannot return anything from this function other than T, such as false or -1. I can of course do this
if(myList.Count > 0)
foo = Utilites.PickRandom(myList);
However there are so many crazy things in C# that I don't know about, and for this app I am creating I very, very often have to choose a random element from a list that could be constantly decrementing in its Count. Is there a better way?