Hello, I faced the need to force one type to another InputData = (TIn) InData , where the aggregate type TIn is used as the type for casting

 public class SerialPortExhangeBehavior<TIn> { public TIn InData { get; set; } private async Task ExchangeService(MasterSerialPort port, CancellationToken ct) { //принудительно приведение к типу TIn var writeProvider = new PanelMg6587WriteDataProvider() {InputData = (TIn)InData}; } } class PanelMg6587WriteDataProvider : IExchangeDataProvider<UniversalInputType, Mg6587Output> { public UniversalInputType InputData { get; set; } public Mg6587Output OutputData { get; } } 

When creating SerialPortExhangeBehavior I close it with the type UniversalInputType

 var SpExhBehavior = new SerialPortExhangeBehavior<UniversalInputType>(); 

And I would like to forcefully convert InputData = (TIn)InData . Even if an exception occurs if the types are not reducible.

please help !!!

    1 answer 1

    If you need a universal “force” cast, do it through object :

      InputData = (UniversalInputType)(object)InData; 

    But there is a good chance that you don’t need it in reality, but you can get by using a constraint on a generic type:

     public class SerialPortExhangeBehavior<TIn> where TIn : UniversalInputType { ... 

    In this case, a type that is not reducible to UniversalInputType will simply not compile.

    • through (object) does not work. As for the architecture curve, you are probably right. And than for me to do where TIn: UniversalInputType is easier not to use generalizations at all, but immediately UniversalInputType. - Aldmi
    • @Aldmi: Hmm, why doesn't it work through object ? What gives? I'm sort of compiled. - VladD
    • Sorry! Late your question was noticed, I already corrected the code, but VS emphasized this cast. - Aldmi 4:02