Note that there are some explanatory texts on larger screens.

plurals
  1. POpolymorphism, generics and anonymous types C#
    primarykey
    data
    text
    <p>Consider the following scenario.</p> <p>Document -> Section -> Body -> Items</p> <p>Document has sections, a section contains a body. A body has some text and a list of items. The items is what the question is about. Sometimes the items is a basic list of string, but sometimes the items contain a list of a custom datatype. </p> <p>So:</p> <pre><code> public class Document { public Section[] Sections{get;set;} } public class Section { public SectionType Type{get;set;} public Body {get;set;} } public class Body { //I want the items to be depending on the section type. //If e.g. the sectiontype is experience, I want the Items to be created with type //Experience. If sectiontype is default I want the Items to be created with type string public Items&lt;T&gt; Items {get;set;} } public class Items&lt;T&gt;:IEnumerable, IEnumerator { // Do all the plumbing for creating an enumerable collection } public class Experience { public string Prop1{get;set;} public string Prop2 {get;set;} } </code></pre> <p>I can´t get this to work. The property Items has to be defined by a type in order to compile. I am stuck here. I can fix this easily by creating a Section class for each of the kind of sections I use. But the thing is that all the other code is the same and all the operations on the section will be the same. The only thing different is the type of list used in the Body.</p> <p>What is the best practice for this. I have tried generics, abstraction etc. I can make it work if creating the Items class directly from the calling program, but I can´t get it to work if Items is declared a property on another class.</p> <p>I can provide more details if needed. Thank you guys and girls for your support.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload