0

In some code I'm looking through the writer goes:

Individual[] candidates = new Individual[tournSize];
for (int i = 0; i < tournSize; ++i)
candidates[i] = population[indexes[i]];
Array.Sort(candidates);

Which property would it sort it by if the class contains: string s; and double d.

PiotrWolkowski
  • 8,408
  • 6
  • 48
  • 68
BinkyNichols
  • 586
  • 4
  • 14
  • possible duplicate of [How to sort an array of object by a specific field in C#?](http://stackoverflow.com/questions/1301822/how-to-sort-an-array-of-object-by-a-specific-field-in-c) – Robert Moskal Apr 22 '15 at 23:50
  • OP's asking specifically what goes on under the hood, not how to sort the array. – Josh L. Apr 22 '15 at 23:51
  • For me, `Array.Sort` just throws `InvalidOperationException`, if array have two or more different not null references. – user4003407 Apr 23 '15 at 01:06

1 Answers1

0

Specified in the documentation, https://msdn.microsoft.com/en-us/library/6tf1f0bc(v=vs.110).aspx, each element must support IComparable, in which case the result is sorted by those definitions, and if an element doesn't support that interface then the result is undefined.

Dax Fohl
  • 10,654
  • 6
  • 46
  • 90
  • public class Individual { public string chromosome; public double fitness; } the classs doesnt inherit from icomparable. yet the code works – BinkyNichols Apr 23 '15 at 00:26
  • @BinkyNichols yes, the spec says the result is undefined however, meaning you can't depend on it, or the result could change from .net 3.0 to 4.0 to 5.0 to 6.0, or from .net to mono. You'd have to look at the .net runtime code to get any guarantees, and ensure that your project never ever ever upgrades .net or even installs a service pack; the spec guarantees nothing. – Dax Fohl Apr 23 '15 at 00:33