0

I know it's possible to set the inheritance behavior of an attribute you've defined:

[AttributeUsage(Inherited = True)]
SomeInheritedAttribute : Attribute
{
}

But can I alter that behavior for a single use of the attribute? My current use case is the [JsonObject(MemberSerialization.OptIn)] attribute. It's inherited by default, and I'd like to change that for individual uses.

One thought was to define my own attribute inheriting from JsonObject:

[AttributeUsage(Inherited = False)]
NonInheritedJsonObject : JsonObject
{
}

But as Mike pointed out, that class is sealed.

Is there a way to mark an attribute instance (terminology?) as non-inherited?

crenshaw-dev
  • 7,504
  • 3
  • 45
  • 81
  • 2
    You won't be able to inherit from JsonObjectAttribute because it is sealed. – Mike Zboray Apr 17 '18 at 17:46
  • You can apply `[JsonObject(MemberSerialization.OptOut)]` to the derived type, it will override the `MemberSerialization` for the base type. – dbc Apr 17 '18 at 18:45
  • 1
    But if you're looking to have different values for `MemberSerialization` for different levels in the inheritance hierarchy, then that is not implemented. See e.g. [Question about inheritance behavior of DataContract #872](https://github.com/JamesNK/Newtonsoft.Json/issues/872) and [caliburn.micro serialization issue when implementing PropertyChangedBase](https://stackoverflow.com/a/29203876/3744182) which indicate that opt-in serialization via `[DataContract]` is inherited throughout the type hierarchy rather than individually controllable on each level in the hierarchy. – dbc Apr 17 '18 at 18:45

0 Answers0