Replace list value by reference
I have a class that looks something like this:
public class Organization
{
public List<IJob> Jobs { get; set; }
public IJob BigBoss { get; set; }
public Organization()
{
BigBoss = new Doctor();
Jobs = new List<IJob>
{
BigBoss,
new Doctor(),
new Doctor()
};
}
}
If I set the BigBoss property to a new value, I would like that value to be updated in the list as well. After BigBoss points out something new, the first item on the list should also. I know the following code won't do it in C # because of the way C # works with links:
static void Main(string[] args)
{
var test = new Organization();
test.BigBoss = new Developer();
//test.Jobs[0] is still pointing to a Doctor, not a Developer
Console.WriteLine(test.Jobs[0]);
}
Is there some other clean way to do this?
source to share
Jobs[0]
refers to BigBoss = new Doctor();
when the constructor is callednew Organization();
When changed: test.BigBoss = new Developer();
Your BigBoss belongs to Developer
, but tasks [0] still belong to the old BigBoss.
You can change your organization as follows:
public class Organization
{
public List<IJob> Jobs { get; set; }
private IJob bigBoss;
public IJob BigBoss { get {return Jobs[0];} set { Jobs[0] = value; } }
public Organization()
{
bigBoss = new Doctor();
Jobs = new List<IJob>
{
bigBoss,
new Doctor(),
new Doctor()
};
}
}
source to share