Best way to work with c# enum

Hi Everybody,

I would like to work with enum in c#.
I tried to implement a custom serializer like this :

[BsonSerializer(typeof(MySerializer))]
    public class MyClass
    {....

public class MySerializer : IBsonSerializer
    {...

And when I tried to call GetCollection on this line :

var test = database.GetCollection<MyClass>(settings.CollectionName);

I receive an error :

Unable to cast object of type ‘Manager.Api.Models.MySerializer’ to type ‘MongoDB.Bson.Serialization.IBsonSerializer`1[Manager.Api.Models.MyClass]’.

Did I forget something?

Thanks.
Best Regards,
Thierry

Hi @Thierry7, and welcome to the forum!

An example class mapping with enum would be as below:

public class MyClass 
{
    public MyType MyType {get;set;}
    public string FooBar {get;set;}
}

// Example enum strings
public enum MyType 
{
    [BsonRepresentation(BsonType.String)]
    TypeA, 
    [BsonRepresentation(BsonType.String)]
    TypeB, 
    [BsonRepresentation(BsonType.String)]
    Default,
}

If you have further question, could you provide:

  • MongoDB .NET/C# version
  • Example documents
  • Minimal reproducible code example
  • Expected outcome of the code example

Regards,
Wan.