using System.Text.Json.Serialization;
[JsonPolymorphic(TypeDiscriminatorPropertyName = "EventType")]
[JsonDerivedType(typeof(EventAlpha), typeDiscriminator: nameof(EventAlpha))]
[JsonDerivedType(typeof(EventBravo), typeDiscriminator: nameof(EventBravo))]
public abstract class EventEnvelope
public Ulid Id { get; init; } = Ulid.NewUlid();
public string Source { get; init; } = "Event.Source";
public DateTime Date { get; init; } = DateTime.UtcNow;
public abstract EventEnvelope.EventData BaseData { get; }
public string SchemaVersion { get; init; } = "1.0";
public abstract class EventData { }
public class EventAlpha : EventEnvelope
public EventAlpha.EventAlphaData Data { get; init; }
public override EventEnvelope.EventData BaseData => Data;
public class EventAlphaData : EventData
public string PropertyZulu { get; init; }
public class EventBravo : EventEnvelope
public EventBravo.EventBravoData Data { get; init; }
public override EventEnvelope.EventData BaseData => Data;
public class EventBravoData : EventData
public string PropertyYankee { get; init; }
public static void Main()
Data = new EventBravo.EventBravoData { PropertyYankee = "tacos rule!" }
var serialized = JsonSerializer.Serialize(evt);
var deserialized = JsonSerializer.Deserialize<EventEnvelope>(serialized);
Console.WriteLine(serialized);
Console.WriteLine(deserialized.BaseData.GetType());
if (deserialized.BaseData is EventBravo.EventBravoData e)
Console.WriteLine(e.PropertyYankee);