imb13
imb13

Reputation: 135

C# - List of generic classes

I have the following classes:

public abstract class Section
{

}

public class Section<T> : Section where T : new()
{
    public string Type { get; set; }

    public bool IsFocused { get; set; }

    private T sectionData;

    public T SectionData 
    { 
        get => sectionData == null ? sectionData = new T() : sectionData; 
        set => sectionData = value; 
    }
}

public class SectionHeaderData
{
    public string Text { get; set; }

    public int Level { get; set; }
}

public class SectionParagraphData
{
    public string Text { get; set; }
}

Then I create sections and store in List<> like so:

Section<SectionHeaderData> sectionHeader = new Section<SectionHeaderData>();
sectionHeader.SectionData.Text = "This is Header.";
sectionHeader.SectionData.Level = 3;

Section<SectionParagraphData> sectionParagraph1 = new Section<SectionParagraphData>();
sectionParagraph1.IsFocused = true;
sectionParagraph1.SectionData.Text = "This is Paragraph 1.";

Section<SectionParagraphData> sectionParagraph2 = new Section<SectionParagraphData>();
sectionParagraph2.SectionData.Text = "This is Paragraph 2.";

List<Section> sections = new List<Section>();
sections.Add(sectionHeader);
sections.Add(sectionParagraph1);
sections.Add(sectionParagraph2);

I am not able to LINQ and get element by IsFocused == true:

var focusedSection = sections.FirstOrDefault(x => x.IsFocused == true);

Is possible to access the SectionHeaderData & SectionParagraphData members like in normal List<SomeClass> list?

Edit 1:

As advised, here is a little more information about what I need.

At some point of the program a function will be called in which I need to get the focused section and to be able to access more specific data of either SectionHeaderData OR SectionParagraphData.

For example, I will need to read / set the value of the Text property.

Upvotes: 3

Views: 461

Answers (1)

Mong Zhu
Mong Zhu

Reputation: 23732

You need to put the properties into the abstract class:

public abstract class Section
{
    public string Type { get; set; }

    public bool IsFocused { get; set; }
}

For example, I will need to read / set the value of the Text property.

I actually wondered why you would not pull the Text property into a base class and solve it with inheritance (I will steal the name from Jon Skeets comment):

public class SectionData
{
    public string Text { get; set; }
}

public class SectionHeaderData : SectionData
{
    public int Level { get; set; }
}

public class SectionParagraphData: SectionData { }

then you can access those fields like this:

var textSection = sections.OfType<SectionData>().ToList();
textSection[0].Text = "this compiles";

Upvotes: 6

Related Questions