user18154574
user18154574

Reputation: 97

Reuse DTO with different child/nested object

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; }
}

Upvotes: 1

Views: 860

Answers (2)

user18154574
user18154574

Reputation: 97

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>

    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; }
    }

Upvotes: 1

StepUp
StepUp

Reputation: 38094

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; }
}

Upvotes: 1

Related Questions