This is the code I would like to write at the end:
var notification = NotificationFactory.FromJson(jsonString);
if (notification is UserUpdateProfileNotification)
{
// notification is of type UserUpdateProfileNotification so I can access notification.Payload.AccoundId
}
This is what I tried so far:
public abstract class Notification<T>
{
public string Type { get; set; }
public T Payload { get; set; }
}
public class UserUpdateProfileNotificationPayload
{
public Guid AccountId { get; set; }
}
public class UserUpdateProfileNotification: Notification<UserUpdateProfileNotificationPayload>
{
public UserUpdateProfileNotification(UserUpdateProfileNotificationPayload payload)
{
Type = "USER_UPDATE_PROFILE";
Payload = payload;
}
}
public static class NotificationFactory
{
public static Notification<object> FromJson(string notification)
{
var parsedNotif = JsonSerializer.Deserialize<Notification<object>>(notification);
if (parsedNotif.Type == "USER_UPDATE_PROFILE")
{
var concreteType = JsonSerializer.Deserialize<UserUpdateProfileNotification>(notification);
return new UserUpdateProfileNotification(concreteType.Payload);
}
throw new NotImplementedException();
}
}
The error I got:
Cannot implicitly convert type 'UserUpdateProfileNotification' to 'Notification'
For me, converting Notification<x>
to Notification<object>
with x inherit from object should be "automatic". But it's not. What's the best way to express this idea in C# (10) ?