Home > OS >  Reuse DTO with different child/nested object
Reuse DTO with different child/nested object

Time:08-25

Imagine I have two DTOs that share top level types (ServerResponseDTO, ServerCallDetails) but the Items object has different child object (ItemsOfTypeA vs ItemsOfTypeB). What would be the best way to reuse defined top level classes without code duplication? - how can I easily instantiate next objects for ItemsOfTypeC, D and so on.

DTO 1:

public class ServerResponseDTO
{
  public int CallId { get; set; }
  public ServerCallDetails Details { get; set; }
}    

public class ServerCallDetails
{
  public int Id { get; set; }
  public Items Items { get; set; }
}

public class Items
{
  public int Id { get; set; }
  public ItemsOfTypeA Items { get; set; }
}

DTO 2:

public class ServerResponseDTO
{
  public int CallId { get; set; }
  public ServerCallDetails Details { get; set; }
}

public class ServerCallDetails
{
  public int Id { get; set; }
  public Items Items { get; set; }
}

public class Items
{
  public int Id { get; set; }
  public ItemsOfTypeB Items { get; set; }
}

CodePudding user response:

I.e. one of the solution might be to use generic type as Items property so now I can easily create new DTO like: ServerResponseDTO<ItemOfTypeC> but is there a way without passing T to very bottom object?:

    public class ServerResponseDTO<T>
    {
      public int CallId { get; set; }
      public ServerCallDetails<T> Details { get; set; }
    }    
    
    public class ServerCallDetails<T>
    {
      public int Id { get; set; }
      public Items<T> Items { get; set; }
    }
    
    public class Items<T>
    {
      public int Id { get; set; }
      public T Items { get; set; }
    }

CodePudding user response:

but is there a way without passing T to very bottom object?

No. Imagine you could write the following:

public class Items
{
  public int Id { get; set; }
  public T Items<T> { get; set; }
}

What would be the type of the foo variable in the following code?

var items = new Items();
var foo = pair.Items;

So you have to declare type where your Items<T> is used:

public class ServerResponseDTO<T>
{
    public int CallId { get; set; }
    public ServerCallDetails<T> Details { get; set; }
}

public class ServerCallDetails<T>
{
    public int Id { get; set; }

    public Items<T> Items { get; set; }
}

public class Items<T>
{
    public int Id { get; set; }

    public T FooBar { get; set; }
}
  • Related