Is is good practice to have same type of list in a class?

Viewed 86

I have created a class and I'm putting a list of same type as a property of that class. Is it good or bad practice?

I am putting the same type of list because of I want to manage everything by only one object. I don't want to create a single object and a list of object of the same type.

Any help is highly appreciated!

class AssetSection
{
    public string Code { get; set; }
    public string Description { get; set; }
    public string SITEID { get; set; }
    public string PlantID { get; set; }
    public string User { get; set; }
    public string UpDateTime { get; set; }

    public List<AssetSection> AssetSections { get; set; }

    public AssetSection(string des, string code)
    {
        Description = des;
        Code = code;
    }
}
2 Answers

That's ok. If you can imagine, you can design and use it.

Let's talk about entity framework. We create 2 entities like this:

public class User : IdentityUser
{
    [Key]
    public string Id { get; set; }
    public UserProfile Profile { get; set; }
}

public class UserProfile
{
    [Key]
    public string UserId { get; set; }
    public User User { get; set; }
}

Now, when we try to get current user:

User user = await _userManager.GetUserAsync(User);

user becomes an instance of User class now. This instance has a property name Profile, and this property has another property name User which has a type User.

It's called mapping. So, to answer your question: You can use it. But I'm not saying it's good or not based on the way to design the model.

As a general observation, such a structure is known as a rose tree, or just a tree. It enables you to write code like this:

var t = new AssetSection("foo", "bar")
{
    AssetSections = new List<AssetSection>
    {
        new AssetSection("baz", "qux")
        {
            new AssetSection("corge", "garply"),
            new AssetSection("fred", "plugh")
            {
                AssetSections = new List<AssetSection>
                {
                    new AssetSection("xyzzy", "thud")
                }
            }
        },
        new AssetSection("quux", "quuz")
        {
            new AssetSection("grault", "waldo")
        }
    } 
};

If what you want to model is a tree-like structure like that, then it's fine. On the other hand, if such a hierarchy is not what you're trying to model, then it's likely to be confusing.

By the way, the code as proposed violates the .NET framework design guidelines:

  • DO NOT provide settable collection properties.
  • DO NOT use ArrayList or List<T> in public APIs
Related