Search code examples
c#umlclass-diagram

How can I work out this part of a class diagram?


For school homework I'm supposed to work out a class diagram in C#. Everything went smoothly, but I'm struggling with the constructor for the Track part.

So I think I have to convert a SectionTypes -> Section to put it in the LinkedList, but this doesn't seem logical to me, or am I missing something? Should I convert it in any way or is my overall code for Section wrong?

Here is the class diagram

The class diagram

Here is the part of Section:

namespace Model
{
    public enum SectionTypes { Straight, LeftCorner, RightCorner, StartGrid, Finish }
    internal class Section
    {
        public SectionTypes SectionType { get; set; }
    }
}

And finally here is where I'm trying to make the constructor, Track:

namespace Model
{
    internal class Track
    {
        public string Name { get; set; }
        public LinkedList<Section> Sections { get; set; }

        public Track(string name, SectionTypes[] sections)
        {
            Name = name;
            // set Sections here
        }
    }
}

The error that I get is CS1503, when I try to add anything to Sections in the front, which means the types aren't the same.

Thanks for reading, and thank you for helping in advance!


Solution

  • Here's what I did. By the way, I renamed the SectionTypes enumeration to SectionType (that way, it reads SectionType.Finish, not SectionTypes.Finish).

    First I created the enum the same as you:

    public enum SectionType
    {
        Straight,
        LeftCorner,
        RightCorner,
        StartGrid,
        Finish,
    }
    

    and the Section class pretty much the same way:

    public class Section
    {
        public SectionType SectionType { get; set; }
    }
    

    I'm not sure why the class diagram is laid out the way it is, but you need to translate a SectionType to a Section in order to get it to work. That's pretty easy; a Section is a pretty stupid/simple wrapper around a single SectionType. So, things end up looking like:

    public class Track
    {
        public string Name { get; set; }
        public LinkedList<Section> Sections { get; set; } = new LinkedList<Section>();
    
        public Track(string name, SectionType[] sections)
        {
            Name = name;
            foreach (var section in sections)
            {
                Sections.AddLast(new Section { SectionType = section });
            }
        }
    }
    

    Note that I construct the Sections LinkedList. It can either be done the way I show, or it could be done in the constructor. But, the magic is to convert the incoming SectionType[] sections into a collection of Section type. I'm sure that there is a way to do this with LINQ (though I don't have a lot of experience with the LinkedList collection). But, doing it explicitly like this makes it more clear.