Monday, October 29, 2012

How to access same List in Class from multiple .cs files?

How to access same List in Class from multiple .cs files?

A fairly simple question I guess.. I'm trying to access a list in a public Class (just an .CS file in my project.).

In one .xaml.cs I access the class by using

DataClass dataClass = new DataClass(); 

When I try to access it in the other .xaml.cs file I used DataClass dataClass = new DataClass(); again. Of course this creates a NEW class (so all the information that is stored inside is not there.

How can I access the Class without creating a new one?

Kind regards, Niels

Answers & Comments...

Answer: 1

You can make the list a static data member in the DataClass and make methods to access it from other classes. Static data member is a shared copy for all the instance of that class. You can make it Concurrent list if the list is supposed to be accessed by different threads using lock. You can use ConcurrentBag for multi-threaded environment. It worth reading singleton pattern that is often used in similar situations.

 public class DataClass   {      public string Timestamp { get; set; }     private static DataClass instance;      private DataClass() { }     public static DataClass Instance      {         get          {             if(instance==null)              {                  instance = new DataClass();              }               return instance;          }      }   }  public class Class1 {      public void SetValue(string str)      {          DataClass ds = DataClass.Instance;          ds.Timestamp  = "value1";      } }  public class Class2 {      public string GetValue(string str)      {          DataClass ds = DataClass.Instance;          return ds.Timestamp;      } }   Class1 c1 = new Class1(); c1.SetValue("hello"); Class2 c2 = new Class2(); string value = c2.GetValue(); 
by : Adilhttp://stackoverflow.com/users/1298762

Answer: 2

There is pattern named Singleton. I guess it can help you.

by : Hamlet Hakobyanhttp://stackoverflow.com/users/685467

Answer: 3

Look over here:

Singleton Pattern

by : SaschaWhttp://stackoverflow.com/users/1622550

Answer: 4

Make it a read only property which instantiates a new instance upon first access like so:

private DataClass dataClass; public DataClass DataClass {     get     {         if(dataClass  == null)         {              dataClass = new DataClass();         }         return dataClass;     } } 
by : MrEdgehttp://stackoverflow.com/users/1506865




No comments:

Post a Comment

Send us your comment related to the topic mentioned on the blog