mardi 8 août 2023

Instantiate a Record in a generic method

I am using a Record as a DTO:

public record AccountTypeDTO(string Id, string Name):IEntityDTOBase;

IEntityDTOBase is used only to access both properties Id and Name.

At this step I'm creating an instance in a generic method like that with reflection:

    internal async IAsyncEnumerable<TEntityDTO> GetAsyncDTO<TEntityDTO>() where TEntityDTO:class,IEntityDTOBase 
    {
        yield return (TEntityDTO)Activator.CreateInstance(typeof(TEntityDTO),Guid.NewGuid().ToString(),"thirdItem" ) ;           
    }

It works but I don't like.

Now I'm trying to follow this track:

    internal async IAsyncEnumerable<TEntityDTO> GetAsyncDTO<TEntityDTO>() where TEntityDTO:class,IEntityDTOBase,new()
    {
        yield return new TEntityDTO() { Id = Guid.NewGuid().ToString(), Name = "thirdItem" };
        
    }
  1. new() is mandatory to be able to create the instance in the generic method.
  2. As I have the new() constraint, the caller of the method complaining must be a non-abstract type with a public parameterless constructor, blà, blà, blà
  3. He also complains about Id and Name in the construction about readonly property

I can implement setters on AccountTypeDTO and parameterless constructor to probably solve the issue but I'll loose the immuability and the benefit of a record, not an option.

Is there any other option to avoid reflection?





Aucun commentaire:

Enregistrer un commentaire