When assigning such values, the result will be unexpected, but I think that it will be evaluated in two cases:
When n is equal to:
(n/2)
When n is odd:
(n/2)+1
If I changed enum as follows:
enum Weekdays {Mon=1,Tue=1,Wen=1,Thi=1,Fri=1,Sat=1, Sun=1, Mon2=1, Mon3=1}
The result will be Fri , now change enum again:
enum Weekdays {Mon=1,Tue=1,Wen=1,Thi=1,Fri=1,Sat=1, Sun=1,Mon2=1}
Now Thi result, change enum again:
enum Weekdays {Mon=1,Tue=1,Wen=1,Thi=1,Fri=1,Sat=1, Sun=1}
Now Thi result, change enum again:
enum Weekdays {Mon=1,Tue=1,Wen=1,Thi=1,Fri=1,Sat=1}
Now the result of Wen , change enum again:
enum Weekdays {Mon=1,Tue=1,Wen=1,Thi=1,Fri=1}
Now the result of Wen changing enum again:
enum Weekdays {Mon=1,Tue=1,Wen=1,Thi=1}
Now the result of Tue , again changing enum :
enum Weekdays {Mon=1,Tue=1,Wen=1}
Now the result is Tue
Although this explains the behavior perfectly, it may not always happen or it may not happen because I did not check for more cases, but since MSDN says you should not assume such an output when enum have the same values ββfor different names ...
However, I think you can easily understand what is going on in your code.
Link: Link
Edit:
@ GrantWinney's answer led me to this, he wrote that Array.BinarySearch is passed an array of values ββand a value for the search, so I understood from the name Array.BinarySearch that it definitely uses BinarySearch and that explains everything ...
Binary search will split the array as follows:
Mid = {Low(which is the starting index) + High (which is the last index of array)}/2
and then check
if (Mid == value) return index; else if the value is smaller or equal move left other wise move right of the array
So this explains how enum values ββare printed if there are several names for the value you are trying to print.
Your original question
enum Weekdays { Mon = 1, Tue = 1, Wen = 1, Thi, Fri, Sat, Sun } Weekdays obj = (Weekdays)1; Console.WriteLine(obj);
It prints Tue because the call to Array.BinarySearch will be executed with an array transfer
{1, 1, 1, 2, 3, 4, 5}
and the value for the search, which is 1 ...
So, BinarySearch will do the following:
Mid = {Low(0) + High(6)} / 2 if (Mid == value) return index else move left
After moving to the left, Mid will be calculated again:
High = Mid - 1; // now only the left sub-array will be searched Mid = {Low(0) + High(2)} / 2 if (Mid == value) return index // here the condition will be true and you will be returned with `Tue`
Second example in your Question:
enum Weekdays { Mon = 1, Tue = 1, Wen = 1, Thi = 1, Fri, Sat, Sun } Weekdays obj = (Weekdays)1; Console.WriteLine(obj);
As I wrote above, the call to Array.BinarySearch and the array will be executed:
{1, 1, 1, 1, 2, 3, 4}
will be passed with value = 1 to search ...
Apply the BinarySearch algorithm to the array and it will evaluate to Thi .