Why is it not possible to set a Public Var? - c#

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

Related

Can static properties return new instances of objects/classes in c#

I am building an application in ASP.NET MVC 4. I am creating a class (similar to Factory type) that will return me instance of my service classes which i have made in BAL Layer. I want to declare static properties in that class and they should return Instance of requested Service Class.
My question is that is it possible that a static propery will return instance of new class because static property will be allocated a memory that will remain throughout the application. I am little confused here, Please explain what happens and what is best way to do so.
Code done so far
public class Factory
{
public static CountryService CountryServiceInstance
{
get
{
return new CountryService(new CountryRepository());
}
}
}
What you should do is write a function the will create the new instances not a get property
public class Factory
{
public static CountryService CreateNewService()
{
return new CountryService(new CountryRepository());
}
}
About your memory concern read Sriram Sakthivel's first comment
More about the Factory pattern here:
http://msdn.microsoft.com/en-us/library/ee817667.aspx
A property in C# is just a method which returns what it should return in its body. In your case, each time you access that property, a new instance of the service will be created.
In case you want only one instance of that service, you might want to store it to the static private variable like this
private static readonly Lazy<CountryRepository> _fact
= new Lazy<CountryRepository>(() => new CountryRepository());
Also, a static properlty never stores something "in the memory throughout the application", but a programmer can do that.
Once again, a property is just a pair of set\get methods, unless you use an automatic property, where there is also a backing field created for the value to store.
A static keyword itself only specifies that a current class member must not be accessed though this keyword, and its value will be shared all across the appdomain (or your application).
your method CountryServiceInstance for each call will always gives you a new instance of CountryRepository.
As you have mentioned, Most of the Factory classes are static which are responsible for creating new object instances. If they give the same object instance none of the factory patterns will serve its intent.
you can undoubtedly proceed with your sinppet..
if you want to quickly validate you can check the created objects hashcode
object.GetHashCode() they will be unique as they are separate objects

Concise Singleton impl that supports reentrancy

I would like to find a concise C# implementation of the Singleton pattern, and I am wondering if it should support the following scenario. What if my singleton's private constructor, as part of initializing the instance, calls a constructor that itself tries to access the singleton currently being initialized? This is what I meant by reentrancy in this question's title. Some would say that a constructor shouldn't do anything complex enough that could lead to this occurring. But what if, due to some future code change within the invoked constructors, it does happen?
I looked through the various answers to this question. I am impressed by the brevity of using Lazy<T>. In the use case I am looking it, it throws an exception which is much better than constructing two instances of the singleton. But alas, in throwing the exception it crashes the app which means it does not support the target scenario.
class Apple
{
static readonly Lazy<Apple> instance = new Lazy<Apple>( () => new Apple(), true );
public static Apple Instance { get { return instance.Value; } }
private Apple()
{
// Call other methods which might access Instance...
var testGet = Instance;
}
}
So I have the idea to instead do the following.
class Banana
{
static Banana instance;
public static Banana Instance { get { return instance ?? new Banana(); } }
private Banana()
{
instance = this;
// Then call other methods which might access Instance...
var testGet = Instance;
}
}
It supports the target scenario, but is anything wrong with it? Is there a better solution?
Please note the following before posting an answer. Like many people, I still consider Singleton as a pattern. Many DI enthusiasts like calling it an anti-pattern. In the context of a project that relies on DI/IoC, this is a reasonable assertion. Outside of that context, however, Singleton is still a valid design pattern. I do not use DI and am not interested in discussing its merit points here. Please do not post an answer below if it will refer to Singleton as an "anti-pattern", or if it will offer "dependency injection" as the solution. Thanks in advance.
Although Singleton may not be considered an anti-pattern, accessing members of an instance before that instance is fully constructed is an anti-pattern. You can't guarantee that code external to the class being initialized doesn't try using some uninitialized state. So the scenario in question should not be supported. If code that attempts to access the singleton is later added to the constructors invoked by the singleton's constructor, then that should trigger a redesign.
Using Lazy<T> as Apple demonstrates is the better approach since it throws an exception on re-entrance rather than accessing an incomplete instance. Lazy<T> additionally supports access from multiple threads, if needed.

If two class inherit an static field, will the objects of those classes share the same value?

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.

c#: (Static) Class-Level Variables

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

Is it bad practice to have state in a static class?

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?

Categories

Resources