2

I have a type that's

 public class Option<T> 
 {
     private bool _hasValue;
     private T _value;
     private Option(T val) { _value = val; _hasValue = true; }
     private Option(bool hasValue) { _hasValue = hasValue; }
     
     public static Option<T> Value(T val) => return new Option(val);
     public static Option<T> Nothing() => return new Option(false);
 }

I wish I could serialize this using protobuf just like a Nullable<T>. ie. is there a way to provide protobuf-net with a custom serializer, that would output nothing if _hasValue is false and that would output the serialized version of _val if _hasValue is true?

Sorry can't seem to find the doc to do this.

edeboursetty
  • 5,669
  • 2
  • 40
  • 67
  • Does this answer your question? [Conditional serialization with protobuf-net](https://stackoverflow.com/questions/35469388/conditional-serialization-with-protobuf-net) – TJ Rockefeller Nov 17 '21 at 16:09
  • Would you permit changes to the class? Direct serialization might require some things to be public. It might be possible to use something like a surrogate, but I'm not sure if that is possible with generic types. – JonasH Nov 17 '21 at 16:16
  • @TJRockefeller: not quite, though the answer to that question is interesting on its own – edeboursetty Nov 17 '21 at 18:40
  • @JonasH: yes the class could be changed. Though really I am interested in knowing if we can supply custom serializers/deserializers – edeboursetty Nov 17 '21 at 18:41

0 Answers0