Best Approach?

  • Thread starter Thread starter Darin
  • Start date Start date
D

Darin

Hi,

I have a winforms app that will need to save certain runtime values that
will need to be accessed by different classes throughout the life of the
app. Is the best approach to create a container class designed as a
singleton class? Any other ideas?

Thanks in advance
 
Darin said:
Hi,

I have a winforms app that will need to save certain runtime values that
will need to be accessed by different classes throughout the life of the
app. Is the best approach to create a container class designed as a
singleton class?

Yes. Singletons give you all the convenience of static data, and all the
flexiblity of instance methods.

Especially with the .NET's extremely elegant singleton idiom:

class MySingleton
{
public static readonly MySingleton instance = new MySingleton();
private MySingleton()
{
//...
}
}


David
 
Hi,

In this case, where this code should be located? In the
main form ?

public class MySingleton
{
public static readonly MySingleton instance = new
MySingleton();
private MySingleton()
{
int defaulttestvalue = 1;
}
}

How from the other classes, will you have access to those
value inside mySingleTon class ?

MySingleton test = MySingleton();

I try few ways, but was unable to have it working.

Carl,
 
Carl said:
Hi,

In this case, where this code should be located? In the
main form ?
It can go in any .cs file, or in MySingleton.cs

public class MySingleton
{
public static readonly MySingleton instance = new MySingleton();
private MySingleton()
{
int defaulttestvalue = 1;
}

}
How from the other classes, will you have access to those
value inside mySingleTon class ?

MySingleton test = MySingleton.instance;

or just

MySingleton.instance.[whatever];

David
 
David Browne said:
Yes. Singletons give you all the convenience of static data, and all the
flexiblity of instance methods.

Especially with the .NET's extremely elegant singleton idiom:

class MySingleton
{
public static readonly MySingleton instance = new MySingleton();
private MySingleton()
{
//...
}
}


See also this survey of better implementations of singleton
pattern in C#:

http://www.yoda.arachsys.com/csharp/singleton.html
 
Back
Top