I have a C# class to store my User details and another for storing JOBS details.The scenario is like each User can have multiple JOBS. I have UserId,UserName,Age etc as my User class properties. Now i want to associate the of JOBS class objects to a property called JOBS so that i can store multiple jobs associated with this user to that as a List. How to write the Property in my USerClass ? .How should be the set and get ?
public class User
{
private List<Jobs> m_JobList = new List<Jobs>();
public List<Jobs> JobList
{
get { return m_JobList; }
}
}
try something like this.
If you want to depend upon abstractions
public interface IUser
{
IList<IJob> Jobs { get; set; }
}
public class User : IUser
{
IList<IJob> Jobs { get; set; } // Automatic properties C# >= 3
public User(IList<IJob> jobs)
{
Jobs = jobs;
}
}
Replace IList
with ICollection
if you don't need indexing and just want a count and be able to enumerate through the jobs. Also consider ReadOnlyCollection<IJob>
if a user can't change jobs (immutable), by removing set;
from interface and replace set;
with private set;
in the class.
You can also use ArrayList as the following:
public class User
{
private ArrayList m_Jobs = new ArrayList();
public ArrayList Jobs
{
get {return m_Jobs;}
}
}
Another two thoughts; you can use C# 3.0 auto props if you like, but you need to use the constructor to do the initial set
:
class User {
public List<Job> Jobs {get; private set;}
public User() {
Jobs = new List<Job>();
}
}
Also; if you are using xml serialization via XmlSerializer
, the property (annoyingly) needs to have a (public
) setter (regardless of whether you use auto-props or an explicit field); much gnashing of teeth over this (also, the class must be public
):
public class User {
public List<Job> Jobs {get; set;}
public User() {
Jobs = new List<Job>();
}
}