Search code examples
c#task-parallel-librarytpl-dataflow

How to Create a List of Type<T1, T2> where T1 & T2 can contain multiple types?


This question involves Task Parallel Library DataFlow.

Consider this statement:

var sampleBlock = new TransformBlock<XDocument, string>
    (xml => TransformXmlToString.Transform(xml));

I want to maintain a list of TransformBlock but the Func transform parameter (TransformXmlToString.Transform(xml)) has me stuck. I can illustrate what I want with the following pseudo-code:

var listOfTransformBlocks = new List<TransformBlock>
{
    new TransformBlock<T1, T2>(t1 => SomeTransformClass.SomeMethod),
    new TransformBlock<T2, T3>(t2 => SomeOtherTransformClass.SomeMethod),
    new TransformBlock<T3, T4>(t3 => YetOtherTransformClass.SomeMethod)
};

How can I achieve the ability to maintain a list of TransformBlock in a way that I will be able to retrieve, link and use (I'd want a similar thing for ActionBlock as well).


Solution

  • You can't have list of items with unrelated types (note that in case of class F<T>{} Foo<One> and Foo<Other> are not related to each other since there is no common parent).

    Since IDataflowBlock is only shared base class/interface for your types you have to do:

    var listOfTransformBlocks = new List<IDataflowBlock> {...}
    

    Unfortunately you'll lose compile-time ability to find types of your transformation and have to write some run-time code to find them back.