0

I'm trying to understand usage of collection in C# and also doing practice on how to define classes base on a statement given in msdn example since its class is not posted and left to reader. I came up with following classes but need to know if it this is right or wrong:

Statement says:

    // ListLeagueList is a list of League objects. 
    // Each League object has a Name and a collection of Division objects. 
    // Each Division has a Name and a collection of Team objects, 
    // and each Team object has a Name.



public class Team
{
    private string teamName;
    public string TeamName
    {
        get { return teamName; }
        set { teamName = value; }
    }
}

public class Division
{
    private string name;
    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    public List<Team> DivisionList;
}


public class League
{
    private string Name;
    public string name
    {
        get { return name; }
        set { name = value; }
    }

    List<Division> DivisionList;
}

Thanks.

gilly3
  • 87,962
  • 25
  • 144
  • 176
amit kohan
  • 1,612
  • 2
  • 25
  • 47
  • Is the structure of classes right? or wrong? if yes, is there a better way to do it? – amit kohan Feb 14 '13 at 01:02
  • 1
    This is not a question, but if you want to know it's right, except for the fact that [Collections should never be null](http://stackoverflow.com/questions/1969993/is-it-better-to-return-null-or-empty-collection), therefore you should change your List fields to properties and make sure they're never null. – Federico Berasategui Feb 14 '13 at 01:04
  • @HighCore I went over the URL you referred but not sure what would be the case of `public static readonly List TeamList = new List();` can you give me an example on this? – amit kohan Feb 14 '13 at 01:39
  • @amitkohan You mean if you should change that into a property? In general I prefer not to expose fields outside classes, but technically it's the same. – Federico Berasategui Feb 14 '13 at 01:42
  • yes, can you show me an example I'm not an expert in it and would love to know it – amit kohan Feb 14 '13 at 01:43

2 Answers2

2

That appears correct, however you've named a List<Team> as DivisionList.. I would change it to TeamList:

public class Division
{
    public string Name { get; set; }

    public List<Team> TeamList { get; set; } // Change this, because its a List of Teams.
}

EDIT:

gilly beat me to the shorthand properties :$

Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
1

You can shorten your property definitions by using Auto-Implemented Properties:

public string Name { get; set; }

This way, you don't need the backing field. If, later on, you need to use a backing field for some reason, add it in at that time.

gilly3
  • 87,962
  • 25
  • 144
  • 176