I would like to do something like this:
public class Foo {
// Probably really a Guid, but I'm using a string here for simplicity's sake.
string Id { get; set; }
int Data { get; set; }
public Foo (int data) {
...
}
...
}
public static class FooManager {
Dictionary<string, Foo> foos = new Dictionary<string, Foo> ();
public static Foo Get (string id) {
return foos [id];
}
public static Foo Add (int data) {
Foo foo = new Foo (data);
foos.Add (foo.Id, foo);
return foo;
}
public static bool Remove (string id) {
return foos.Remove (id);
}
...
// Other members, perhaps events for when Foos are added or removed, etc.
}
This would allow me to manage the global collection of Foos from anywhere. However, I've been told that static classes should always be stateless--you shouldn't use them to store global data. Global data in general seems to be frowned upon. If I shouldn't use a static class, what is the right way to approach this problem?
Note: I did find a similar question, but the answer given doesn't really apply in my case.
Who stays that static classes should be stateless? Static means stated.
Just know how static classes work in the CLR:
You can't control the time when static constructors are called.
Static classes have a separate state for each calling program.
Also be aware of concurrency issues.
As a side note, it amazes me how often people say "Don't use X." It would be like someone walking into your toolshed and pointing to half a dozen tools and saying, "Those tools are bad practice." It doesn't make sense.
Global data is both powerful and a common source of problem, that's why techniques like dependency injection are used. You can think of it as a normal decoupling problem. Having global data that is referenced directly in a lot of places in your program makes a strong coupling between that global data and all those places.
In your example however you have isolated the access to the data into a class, which controls the exact details of the access of the global data. As some global data is often inevitable, I think that this is a good approach.
You can for example compare to how app.config and web.config are used through the .NET framework. They are accessed through a static class System.Configuration.ConfigurationManager with a static property AppSettings, which hides a away the details of how to reach the global data.
What you seem to be looking for here is a singleton class, not a static class. Static classes and methods should be referred for stateless routines. A singleton class gets instantiated once and only once per application run and has the full functionality of a class as such. Every time that you reference it in the future, you will get back the exact same instance with the exact same member properties.
The first google result for "C# singleton" seems to have a pretty decent explanation for implementation. http://www.yoda.arachsys.com/csharp/singleton.html
It's not generally bad. In some rare cases it's neccessary to do it that way than implementing something else with large overhead.
But it's recommended to watch for threadsafety.
You should lock every call to your dictionary so that only one thread can access it at one time.
private static readonly object LockStaticFields = new object();
public static Foo Add (int data) {
lock(LockStaticFields)
{
Foo foo = new Foo (data);
foos.Add (foo.Id, foo);
return foo;
}
}
Use a read only static property in your class, this property will be the same across all instances of the class. Increment it and decrement as needed from the constructor, etc.
I use lists in static classes all the time for things that will never (or extremely rarely) change - handy for for loading pick lists and such without hitting the db every time. Since I don't allow changes, I don't have to worry about locking/access control.
One other thing to take into consideration is the application itself and the budget for it. Is there really a need for something more complex than a static class?
Related
Is there a way I can initialize a class which contains a static constructor (that throws an exception), without executing the static constructor?
I've tried these so far:
Activator.CreateInstance(typeof(Foo));
FormatterServices.GetUninitializedObject(typeof(Foo));
var s = new XmlSerializer(typeof(Foo));
Foo f = (Foo)s.Deserialize(new StringReader("<Foo></Foo>"));
Aside from using a CRL Profiler api with something like MS Fakes or TypeMock, can this be done using any API in the baseclass library, or perhaps something unmanaged.
Example class that I want to use.
public class Foo
{
static Foo()
{
throw new Exception("Populate Bar from the database, which isn't available.");
}
public int Bar { get; set; }
}
No, not that I'm aware of, at least directly.
Static constructors are there exactly to be automatically called whenever anything happens either to anything (method, property, ...) static from the class, or when you create the very first instance of that class (if it's possible).
This means, basically, that they are kind of always called, whether you like/want it or not. It's always automatic and it always happens.
One option, though, would be to use some nasty reflection to extract working code, replace (or entirely remove) static constructor and rebuild the class from scratch.
This might help a bit on this.
Problem is that another great question arises: how to replace that type during its usage. If it comes from an interface, it might be easier, but if it's a concrete type being directly called, you have got yourself a great challenge.
Now, if you take this to a higher abstraction level, this issue might be solved using other approaches, like proxying that request to some other database, or even translating it to another language.
Is it possible that different objects of different classes can use one shared item among themselves (e.g for providing some information on the fly) or better a means of communication between different objects of two different classes ?
Class Base
{
public static string SomeThing = "Shared With All";
}
Class Der1 :Base
{
public void DoSomeThing()
{
SomeThing = "SomeThing Goes in here...";
}
}
Class Der2 :Base
{
public void DoSomeThingElse()
{
Console.WriteLine"(SomeThing);
}
}
....
{
Der1 dr1 = new Der1();
dr1.DoSomeThing();
Der2 dr2 = new Der2();
dr2.DoSomeThingElse(); //shows 'SomeThing Goes in here...'
}
If it helps more, I am trying to create a designer of some kind and so I need to get track of all controls and their associations on the designer. Actually there are only two objects at the moment (one called transaction and the other is called place, different places can be associated with different transactions, and this association is done by the user clicking on one place and pointing to the other transactions (have you seen Proteus? something like that).
So this approach will help me know which object is referring which other object and thus and association between the two can be easily spotted and saved.
The static field isn't really inherited in the same way as normal fields are. There's still just one static field, Base.SomeThing. Both of your derived classes are referring to the same field: if anything changes Base.SomeThing, everything that accesses that field will see the change.
Yep, you've invented a global variable :) It is also almost always a sign of bad design. Try solving your task differently.
It is possible, but think carefully about communicating in this way inside the class. There is no good way to account for concurrency issues and very hard to debug if the value is set multiple places.
You can either use static var's or share stuff using setter and getter. These are basic operators in OOP.
A static field belongs to the class that declares it. Any subclasses of that class gets access to that one static field.
There are some caveats here. Declaring a static variable on a Generic class means that one copy of that variable exists for each closed type of that generic. Here's an example to clarify
public class StaticGenericTest<T>
{
private static int count=0;
public StaticGenericTest()
{
count++;
}
}
If you instantiate a StaticGenericTest<int> and a StaticGenericTest<string> they would have different values for count. However a subclass of StaticGenericTest<int> would share count with all other subclasses of StaticGenericTest<int>.
Also you'll get funny behavior using the ThreadStatic attribute (because you'll get one copy of count per thread) and/or static constructors.
As someone mentioned, Static fields are global state and should be protected as such and used with caution.
I am trying to set the following public var:
var collection = new Dictionary<string, Statistics>();
I want to be able to use the same collection all through my application and i therefore want to create it right at the top when the applications starts.
How would i do this?
There is no concept of a global variable in C#. You always have to declare variable inside some class/scope.
What you can do, is to make it accessible via public modifier, like a property (say).
Just an idea:
public class Shared
{
public Dictionary<string, Statistics> CollectionDic {get;set;}
public Shared() {
CollectionDic = new Dictionary<string, Statistics>();
}
}
After you can access it like:
var shared = new Shared();
shared.CollectionDic.Add(..)
...
You have to workout by yourself, what fits your exact needs.
You can create it as a public static field or property in public class (optionally also static):
public class Variables
{
public static Dictionary<string, Statistics> collection = new Dictionary<string, Statistics>();
}
Then access it in code:
Variables.collection.Add(...);
Note that it is not thread-safe approach. So if you intend to use static dictionary in multithreading app, it's better to either have static methods, wraping the dictionary in thread-safe way (as Jon Skeet mentioned) or use thread-safe collections, for exapmle ConcurrentDictionary.
The error you are getting is:
The contextual keyword 'var' may only appear within a local variable
declaration
I believe you are trying to define your collection as:
public partial class Form1 : Form
{
var collection = new Dictionary<string, Statistics>();
You can't use var keyword at this level,
I want all of my Form1.cs to access it, not different .cs files
You may define it like:
Dictionary<string, Statistics> collection = new Dictionary<string, Statistics>();
It will be available to all the methods inside the Form1 class
EDIT
The comments of the OP showed, that the requirement is only to be able to access the variable through the one .cs code. Please disregard the following, and please vote delete if you think that this answer is not a valuable addition to the question for future visitors of this topic. Or vote up, if you think it has enough added value to stay.
What I meant for the original question, regarding I want to be able to use the same collection all through my application
In an object oriented environment, if this is a requirement that can not be surpassed by refactoring/restructuring the application, you should definitely use the Singleton design pattern
A singleton is a pattern, which guarantees that only one instance of the given class exists (per application contex/virtual machine, of course), and that that instance can be accessed from everywhere in the context of the same application.
That is:
create a class (e.g. by name MyDictionary)
implement the necessary functions you want from it (you want this to be independent of the underlying implementation)
make it a singleton by following the article
decide if you need lazy loading
I'd recommend to always use thread safe implementation when dealing with singletons to avoid unwanted consequences.
access from whenever you like
Example: (from the C#Indepth link, second version, having simple thread safety, take note who the author of the article is!)
public sealed class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
BEWARE always take thread safety into count!
As I got a response from #JonSkeet (yikes!), I think I have to explain the rationale behind my answer:
Pros:
It is better than having some non-standard way of doing so
It is better than having to pass it around to every bit of code that exists
Cons:
It is absolutely not recommended, if this requirement can be circumvented by any means
having a singleton map around is a serious bad smell: keeps references throughout the life of the application, leading to massive leaks more often than not
multithreaded behaviour is something that is not trivial, and especially difficult to go after if something misbehaves only very rarely (hidden race conditions, and whatever else lurking under the bed of a programmer during nightmares)
Also recommended reading:
Singleton pattern Wiki
MSDN: Implementing Singleton in C#
Clarification of the article on C#Indepth on Stack overflow - by the author himself
This is definitely a bit of a noob question, but my searches so afar haven't cleared the issue up for me.
A want a particular console app to store several class-level variables. In one case, I want to store a copy of my logging object, which I'll use in various places within the class. In another case, I want to store a simple type, a int value actually, which is only going to be used internally (doesn't need to be a property).
It appears that unless I specify these variables as static, I can't use them in Main() and beyond.
My understanding of static objects is that their values are shared across all instances of an object. Under normal operation, I'd expect their to be only one instance of my app, so this issue isn't a problem - but it has highlighted a lack of understanding on my part of something that is fairly fundamental.
In the case, of my logging object, I could see a case for making it static - sharing a log across multiple instances might be a benefit. However, it might not be the case... In the case of my int, I'd certainly never want this to be shared across instances.
So...
Am I misunderstanding the theory behind this?
Is there a different way I should be declaring and using my class-level variables?
Should I be avoiding using them? I could simply pass values as parameters from function to function, though it seems little a lot for work for no apparent gain.
EDIT: OK, the message is clear - my understanding of statics was largely correct, but the problem was one of structure and approach. Thanks for your replies.
Just encapsulate your application in another class, which you create and execute on the Main method:
class MyApp {
private MyLog lol = new MyLog();
private int myInt = 0;
public void Execute() {
// ...
}
}
class Program {
public static void Main() {
new MyApp().Execute();
}
}
You can still make the log field static if you want.
You should be creating a class outside of your Main function, and then creating an instance of that class from within Main.
EG
class MyConsoleApp
{
public static void Main()
{
MyClass mc = new MyClass();
}
}
Class MyClass
{
private MyLog lol as new MyLog();
private int myInt = 0;
}
The issue here is more or less purely syntactical: Because a static method can only access static fields, and the Main() method has to be static, this requires the used variables to be static. You never create an instance of the MyConsoleApp class.
Not really much theory here, only pragmatic requirements...
Thomas
I have a class called DataStructures where I have a set of public static data structures that store objects. To add an object to a data structures is an involved process requiring a number of checks to be carried out, processes to be remembered and data to be rearranged. In another class called Foo, I need to add objects to the data structures.
I was thinking I can do this by making a method called ObjectFeed which would take an object and the object's label as parameters. The label would tell the method which of the data structures the object should be added to. I would also have a method called addObject which would take the object to append and the appropriate target data structure as parameters:
Public Class DataStructures
{
public static List<obj> object1Storage = new List<obj>();
public static List<obj> object2Storage = new List<obj>();
...
}
Public Class Foo
{
public void ObjectFeed(/* PARAMETERS */)
{
//Code that generates an object called inspectionObject
//inspection object has an associated enum Type
if(objectType == Type.Type1)
{
addObject(inspectionObject, DataStructures.object1Storage);
}
if(objectType == Type.Type2)
{
addObject(inspectionObject, DataStructures.object2Storage);
}
...
}
private void addObject(obj inspectionObject, List<obj> objStorage)
{
objStorage.Add(inspectionObject);
//And a lot more code
}
}
Passing a public data structure as a parameter to a method that can just as well access that data structure directly doesn't feel correct. Is there a more clever and less intuitive way of doing this?
Edit:
In the example I originally contrived, the ObjectFeed method served no apparent purpose. I rewrote the method to look more like a method from the real world.
Where is the object type coming from? Passing a string value as a type of something is very rarely a good idea. Consider different options:
Create an enum for these values and use this. You can always parse it from string or print it to string if you need to.
Maybe it makes sense to have a couple of specific methods: FeedObjectType1(object obj), etc.? How often will these change?
Its really difficult to give you a definite answer without seeing the rest of the code.
Exposing public static lists from your DataStructures class is in most cases not a good design. To start with I would consider making them private and providing some methods to access the actual functionality that is needed. I would consider wrapping the lists with the addObject method, so that you don't have to pass the list as an argument. But again I am not sure if it makes sense in your case.
You seem to use DataStructures like some kind of global storage. I don't know what you store in there so I'm going to assume you have good reasons for this global storage.
If so, I would replace each list with a new kind of object, which deals with additions of data and does the checks relevant for it.
Something like:
interface IObjectStorage
{
void Add(object obj);
void Remove(object obj);
}
Each object storage type would derive from this and provide their own logic. Or it could derive from Collection<T> or something similar if collection-semantics makes sense. As your example is right now, I can't see the use for ObjectFeed, it serves as a fancy property accessor.
Selecting which property to access through a string sounds iffy to me. It is very prone to typos; I would rather use Type-objects available from any object in C# through the GetType-method or typeof() construct.
However. The whole setup feels a bit wrong to me, DataStructures et al.
First, testing your static class will be hard. I would pass around these stores to the types that need them instead. Replacing them with other stuff will also be hard, using interfaces will at least not tie you to a concrete implementation, but what if you want to use another location to store the objects in other code? Your static class is no longer relevant and you'll need to change a lot of code.
Maybe these things are out of your control, I don't know, the example code is a bit vague in that sense.
As pointed out in other answers:
The public static Lists are bad practice
Since the addObject method is the same for every data structure, it should be implemented as a data structure accessor.
To this end, I moved the instantiation of the data structures into Foo and moved the addObject method from Foo to a new class called StorageLibrary that more accurately represents the data structure architecture.
private class StorageLibrary
{
private List<obj> storedObjects = new List<obj>();
public void addObject(obj inspectionObject)
{
storedObjects.Add(inspectionObject);
//And a lot more code
}
}
public class Foo : StorageLibrary
{
//Declaration of libraries
public static StorageLibrary storage1 = new StorageLibrary();
public static StorageLibrary storage2 = new StorageLibrary();
...
private void ObjectFeed(/* PARAMATERS */)
{
//generate objects
if (objectType == Type.Type1)
{
storage1.addObject(inspectionObject);
}
if (objectType == Type.Type2)
{
storage2.addObject(inspectionObject);
}
...
}
}