Question

i am creating a C# class library that reads data from a socket and store some data in a list. This list will change more the once per second during execution time.

In need this list to be the content of a dataGridView of a winforms application, but i'm wondering how can i expose it out of my library.

Is it safe to declare the List as public in the classLibrary like:

public class THRManager
{
    public List <GaugeItem> outSource;
    ...

and then on the WinForm side:

public TMRMainForm()
{
    THRManager thrC = new THRManager();
    dataGridView1.DataSource = thrC.outSource;
    ...

Is this safe? If not, what's the best way?

Thx!

==================EDIT

Should i use DataTable or BindingSource ?

Was it helpful?

Solution

Use a ReadOnlyCollection but create it once in your constructor or where ever else you need them, in order not to do new ReadOnlyCollection... every time you access it.

public class THRManager
{
   private List<GaugeItem> outsource;
   private ReadOnlyCollection<GaugeItem> outSourceReadOnly;

    public THRManager()
    {
        outSource = new List<GaugeItem>();
        outSourceReadOnly = new ReadOnlyCollection<GaugeItem>(outSource);
    }

    public ReadOnlyCollection<GaugeItem> OutSource 
    { 
        get { return outSourceReadOnly; } 
    }
}

Hope code works without syntax errors :)

OTHER TIPS

This is a safer option when publishing an inner collection.

private List<GaugeItem> outSource;

public ReadOnlyCollection<GaugeItem> OutSource 
{ 
    get { return new ReadOnlyCollection<GaugeItem>(outSource); } 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top