lundi 14 octobre 2019

how to instantiate the collection/class based on a property in C#

Below are my DTOs.

public class Movie
{
  public int Id {get; set;}

  public string Name {get; set;}

  public IEnumerable<BasicTicket> Tickets { get; set;}

}

Ther are multiple types of Ticket of type BasicTicket

public class BasicTicket
{
   public int Id {get; set;}

   public bool IsSpecial { get; set;}

   public bool IsDicount{get; set;}
   public decimal Price { get; set;}
}

1

public class SpecialTicket : BasicTicket
{
  public string SpecialProp1 {get; set;} //n such properties where n could be the range of 2 to 10
}

2

public class DiscountTicket : BasicTicket
{
  public string SomeProp1 {get; set;} //n such properties where n could be the range of 2 to 10
}

& so on

Now basis on the boolean property present in the Movie, the collection of Ticket to be initialized accordingly.

One such try:-

public IEnumerable<Ticket> Tickets { 
     get { return Tickets;} 
     set 
     { 
       if(this.IsSpecial)
       {
           value = new List<TicketSpecial>();
       }
       else
       {
           value = new List<Ticket>();
       }
     }

But doing so, when I debug I don't see any error message, simply debugging stops

In Actually these all are DTO for APIs. So also tried this.

WebAPI Controller

public class MovieController : ControllerBase
{

  public IActionResult Post([FromBody]Movie movie)
  {
      if(movie.IsSpecial)
      {
         var tickets = movie.Tickets;
         movie.Tickets = new List<TicketsSpecial>(); 
          movie.Tickets = tickets; // Throws error or doesn't get the values of the props present in TicketSpecial
         movie.Tickets = tickets;
      }
  }

  private bool SomeMethod(IEnumerable<TicketSpecial> tickets)
  {
  }
}

Also, wanted to know if adding properties to BasicTicket (if n= 2 or 3)on fly using ExpandoObject would be good or not?

I think there would be some design pattern that would rightly address this object creational but didn't find anything yet.

Thanks!

Aucun commentaire:

Enregistrer un commentaire