Which of these two GetLargestValue C# implementations is better, and why?
.net, .net-2.0, c#
Solution
Ôption B of course.
A is ugly :
Catch(Exception) is a really bad practice
You shoul not rely on exception for null ref, out of range,...
Sorting is way complexier than iteration
Complexity :
A will be O(n log(n)) and even O(n²) in worst case
B worst case is O(n)
Problem
I'm having a disagreement with someone over how best to implement a simple method that takes an array of integers, and returns the highest integer (using C# 2.0). Below are the two implementations - I have my own opinion of which is better, and why, but I'd appreciate any impartial opinions. Option A ``` public int GetLargestValue(int[] values) { try { Array.Sort(values); return values[values.Length - 1]; } catch (Exception){ return -1;} } ``` Option B ``` public int GetLargestValue(int[] values) { if(values == null) return -1; if(values.Length < 1) return -1; int highestValue = values[0]; foreach(int value in values) if(value > highestValue) highestValue = value; return highestValue; } ```