[CSHARP-2759] Specify elements of SortDirection enum with appropriate values of MongoDB Created: 27/Sep/19  Updated: 30/Sep/19  Resolved: 30/Sep/19

Status: Closed
Project: C# Driver
Component/s: Feature Request, Serialization
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Major - P3
Reporter: Valeriy Abakumov Assignee: Robert Stam
Resolution: Won't Do Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Now the elements of enum `SortDirection` does not have int numbers:

```csharp

public enum SortDirection

{     Ascending,     Descending }

```

Because of this, a lot of logic in the code of `MongoDB.Driver` library to verify compliance with the elements and numbers (-1 and 1) like this:

```csharp

switch (_direction)

{     case SortDirection.Ascending:         value = 1;         break;     case SortDirection.Descending:         value = -1;         break;     default:         throw new InvalidOperationException("Unknown value for " + typeof(SortDirection) + "."); }

```

This is unnecessary logic, because the C# has built-in casting enum to Int32 via setting numbers for appropriate enum elements. So the enum `SortDirection` might be refactored like this:

```csharp

public enum SortDirection

{     Ascending = 1,     Descending = -1 }

```

In this case no more additional logic needed. And in the future, if this numbers will be changed (for example, `100` for `Ascending` and `200` for `Descending`), there is one place to change code - `SortDirection` enum.

Any string representation of `SortDirection` enum elements looks like this:

```csharp

$"ascending is: {(int) SortDirection.Ascending}"

```



 Comments   
Comment by Robert Stam [ 30/Sep/19 ]

It's an interesting suggestion, but I would summarize our thinking about it like this:

  1. The SortDirection enum represents the abstract concept of Ascending or Descending, independent of how that concept is represented in the query language
  2. The abstract SortDirection is translated to 1 or -1 when translating abstract queries to actual queries

Note also that a simple cast to int does not check whether the value is valid. For that we'd still need a switch statement anyway.

 

Generated at Wed Feb 07 21:43:28 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.