user1017882
user1017882

Reputation:

Get/Set for a Private Static Collection?

I've defined a class with the following property:

 private ObservableCollection<Job> allJobs;

Access is defined as follows:

    public ObservableCollection<Job> AllJobs
    {
        get
        {
            return this.allJobs;
        }
        set
        {
            this.allJobs = value;
        }
    }

The get set works fine when I assign a whole ObservableCollection to the property, the set works fine for retrieving it obviously. But why have I lost all the methods that normally allow me to 'Add' (i.e. add 1 job to the collection)?

At the moment I'm having to create a temporary collection to populate to then assign to the allJobs property and I shouldn't have to.

Any ideas??

Upvotes: 3

Views: 1404

Answers (2)

Johannes Kommer
Johannes Kommer

Reputation: 6451

What do you mean with 'lost methods'? Have you tried AllJobs.Add()? The following code works for me:

void Main()
{
    AllJobs = new ObservableCollection<Job>();
    AllJobs.Add(new Job());
}

public class Job { }

private ObservableCollection<Job> allJobs;

public ObservableCollection<Job> AllJobs
{
    get
    {
        return this.allJobs;
    }
    set
    {
        this.allJobs = value;
    }
}

EDIT:

Based on your comment I've amended my code as follows but everything still works for me, I have noticed however that you don't seen to initialise the allJobs collection anywhere.

void Main()
{
    PresentationManager.Instance.AllJobs.Add(new Job());
}

public class Job { }

sealed class PresentationManager 
{ 
    public static readonly PresentationManager Instance = new PresentationManager(); 

    private PresentationManager()
    {
        allJobs = new ObservableCollection<Job>();
    }

    private ObservableCollection<Job> allJobs; 
    public ObservableCollection<Job> AllJobs 
    { 
        get { return this.allJobs; } 
        set { this.allJobs = value; } 
    } 
}

Upvotes: 4

GeirGrusom
GeirGrusom

Reputation: 1019

Normally you wouldn't want a setter for such a property, as you would lose all events bound to the ObservableCollection when the setter is used.

public ObservableCollection<Job> AllJobs { get; private set; }

Upvotes: 1

Related Questions