Home > Mobile >  Why the method uses Activator.CreateInstance instead of directly "new Class()"?
Why the method uses Activator.CreateInstance instead of directly "new Class()"?

Time:02-13

In the method GetNotificationCorrespondingToDomainEvent in https://github.com/jasontaylordev/CleanArchitecture/blob/main/src/Infrastructure/Services/DomainEventService.cs, it has the following method,

private INotification GetNotificationCorrespondingToDomainEvent(DomainEvent domainEvent)
{
    return (INotification)Activator.CreateInstance(
        typeof(DomainEventNotification<>).MakeGenericType(domainEvent.GetType()), domainEvent)!;
}

How it compares with new DomainEventNotification(....)? BTW, is the ! at the end necessary?

private INotification GetNotificationCorrespondingToDomainEvent(DomainEvent domainEvent)
{
    return new DomainEventNotification<DomainEvent>(domainEvent)!;
}

CodePudding user response:

The difference is that

return (INotification)Activator.CreateInstance(
        typeof(DomainEventNotification<>).MakeGenericType(domainEvent.GetType()), domainEvent)!;

creates an instance with the dynamic type of domainEvent. So if the actual argument is MyDerivedDomainEvent, it creates an instance of DomainEventNotification<MyDerivedDomainEvent>. There's not enough context to tell whether that makes sense, but that's what happens.

Activator.CreateInstance() has the return type object?, so the ! is necessary to prevent the nullability warning. One could question why they selected the return type to be nullable, because I don't think it will ever return null.

  •  Tags:  
  • c#
  • Related