I've read through Is it possible to assign a base class object to a derived class reference with an explicit typecast? and want to know if JsonConvert is the best solution in this scenario. I have an existing C# project that makes calls to a web API and returns the data to various clients (Blazor, WinForms, Xamarin, command line, etc.). The problem is that client-specific properties have been added to the data classes. I want to strip out the client-specific code and put them into a derived class. Example call:
public class ResponseModel<T>
{
public long StatusCode { get; set; } = -1;
public T? Result { get; set; }
public List<T>? Results { get; set; }
public string Message { get; set; } = string.Empty;
}
public class PromoItem
{
public Guid PromoItemId { get; set; }
public string ItemName { get; set; }
public bool IsAvailable { get; set; }
public int MaxAllowed { get; set; }
public string ItemManufacturer { get; set; }
public int QtyTotal { get; set; }
public int QtyDistributed { get; set; }
public Guid CreatedById { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedOn { get; set; }
public Guid ModifiedById { get; set; }
public string ModifiedBy { get; set; }
public DateTime? ModifiedOn { get; set; }
}
ResponseModel<PromoItem> response = await PromoItemService.Get(Guid.Parse("73F166A6-C576-4531-83D5-154B4D16E557"));
Each client app is can do something different with the data. For example, I've stripped this out into a derived class:
public class PromoItemDTO : PromoItem, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public string ItemTypeGlyph
{
get
{
if (ItemName.Contains("Shirt"))
{
return "\uE8D7";
}
else if (ItemName.Contains("Shoes"))
{
return "\uE8AB";
}
else
{
return "\uE8D7";
}
}
}
bool isItemVisible;
public bool IsItemVisible
{
get { return isItemVisible; }
set
{
isItemVisible = value;
OnPropertyChanged(nameof(IsItemVisible));
}
}
public void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
So should I be using JsonConvert to convert ResponseModel.Result to a PromoItemDTO object in this scenario? Should I use composition? Or something else?