[CSHARP-682] Enum support for Update<T>.BitwiseAnd and Update<T>.BitwiseOr Created: 15/Feb/13  Updated: 20/Mar/14  Resolved: 27/Mar/13

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

Type: Improvement Priority: Minor - P4
Reporter: Manuel Warum Assignee: Robert Stam
Resolution: Done Votes: 0
Labels: bitwise, c#, driver, enum, update
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Backwards Compatibility: Fully Compatible

 Description   

I am using MongoCollection<T> in my project a lot, where T are my root domain objects (ie. not BsonDocument). In one instance, I am trying to use flags to indicate data such as user roles. As roles are not mutually exclusive in this particular case, they are designed as enums with the [Flags] attribute to allow for multiple roles. For example:

[Flags]
public enum Roles
{
    User = 0x00,
    Moderator = 0x01,
    Administrator = 0x02,
    SomeOtherRole = 0x04,
    /* etc */
}

As I was trying to do an Update<T>.BitwiseAnd or Update<T>.BitwiseOr, I noticed that the method only takes Func<T, int> or Func<T, long> as their first argument and int or long as their second. Since my models make use of enums, expressions like these make my compiler unhappy:

userCollection.FindAndModify(..., ..., Update<User>.BitwiseOr(x => x.Roles, roles));

(This snippet is of course abbreviated, there's Query<T> and SortBy<T> expressions instead of just ellipses. "roles" is an instance of that Enumeration here.)

I would be happy if you would consider directly supporting enumerations in this use case that does not require me to make use of int or long in my models to represent flags.



 Comments   
Comment by Robert Stam [ 21/Mar/13 ]

Not sure how to implement this given that C# doesn't allow type parameters of generic methods to be constrained to enum. For example, the following is not legal C#:

public static UpdateBuilder<TDocument> BitwiseOr<TEnum>(Expression<Func<TDocument, TEnum>> memberExpression, TEnum value) where TEnum : enum

So I don't know how we could provide an overload of BitwiseOr that worked with enums directly.

However, the following does work:

userCollection.FindAndModify(..., ..., Update<User>.BitwiseOr(x => (int)x.Roles, (int)roles));

It's not perfect, and you have to know that the underlying representation of the enum is an int (or a long). But it's at least better than dropping down to the untyped builder.

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