Static keyword, state / instance variables and thread safety

First of all, the static keyword.

I read several articles and past topics that show the static keyword. I did not find many scripts listed in when I should use it. All I know is not creating an object on the heap that tells me that it would be good in terms of performance for an object that has been used a lot.

Is there any other reason to use it?

In addition, I read something about the static keyword and how it cannot be used with instance variables or change state. Can anyone clarify this? This seems to be a 2 + 2 case, but I cannot get an answer (a few basic and simple knowledge is missing).

Finally, on thread safety, what should I look for in my code to get an idea of ​​thread safety?

I posted this in VB.NET too, because I don't think different languages ​​(C # / VB.NET) will have different rules.

thanks

+4
source share
7 answers

A static keyword means something else in C, but in C # and Java it declares methods and variables as a class, not an object.

You would like to use it for methods and variables that do not need data from a specific object, but use the same data for each object of this type.

For example, String.Format () is a static method of the String class. You call this in your code without creating an instance of String. Similarly, Math.Pi will be a class variable.

But something like a length method makes no sense if it does not act on a particular instance of the string, so it should be an instance method. For example, x = "hello" .Length ();

So, if you want your method to be called only with the class name and not with the object, you make a static method. Note that such a method can only refer to static variables and call static methods, since it does not have an object with which you can refer to non-static elements.

In C, the static keyword denotes a file scope. A static variable or top-level function does not get its name exported to another compiled object code. Thus, two files can declare static variables with the same name, and not create a conflict. We do not have this problem in C #, because there are namespaces, as well as private, protected and public keywords, to indicate visibility.

Another value for static variables inside a function in C. These variables retain their value between function calls. For example, you can use it to count the number of times a function has been called. Static variables in C # also have this property, but you do not declare them inside a method, as in C, only inside a class.

+4
source

Finally, on thread safety, what should I look for in my code to get an idea of ​​thread safety?

Writing thread-safe code is an important topic that I will not go into, but I will say one thing about static and thread safety.

Most of the methods for enforcing code for multiple call flows involve some kind of object instance blocking. You will notice that in the .NET framework (BCL) all static members are thread safe. This is due to the fact that there is no clear way to find out which instance of the object should be blocked in order to share this resource between all conceivable subscribers.

Old recommendations used to indicate a lock of the type itself, i.e.

lock (typeof(SomeType)) { SomeType.SomeStaticMethod(...); } 

This approach is now discouraged and impractical because there is no way to control the order of access to these lock objects in all conceivable call flows. Blocking on public objects (including ICollection.SyncRoot , which is now deprecated for the same reason) opens the door to deadlock blocks. In the above example, an instance of the type is public and should not be blocked.

Given that there is no single instance that all clients of static methods can reasonably agree to use to access static members, the Microsoft BCL team had to make all static members typical. Fortunately for them, static members are few and far between.

+1
source

If you want to keep something unique for each instance, it must be an instance variable. You can make other data static if you think it is not unique to each instance (or does not require instantiation).

eg. String.Empty (which is the public variable static readonly). Using this does not require creating a new instance of the string.

0
source

I use static variables to store values ​​(e.g. sql queries) that are read from files, in functions that will be called alot (as in a loop). Prevents a disk hit on every function call and is a good use of "information hiding".

0
source

I think this answers my questions very well (covers usage):

http://msdn.microsoft.com/en-us/library/79b3xss3.aspx

0
source

In fact, static variables are NOT on the stack, they are stored in a special memory segment, in which there is no stack or heap. In addition, regardless of whether the variable is on the heap or the stack, the performance impact will not be affected at all.

Static function variables are variables that exist in a function, and if the changes retain their meaning between calls. They can be considered as global values ​​that are initialized on demand and can only be used in the function in which they are declared. IMO really has no good reason to use static variables in functions other than random bits of testing.

Static member variables are variables shared between all instances of the class. Therefore, if your "Person" has a static member named "mCountry", then all people will share this variable. If one person changes him, he changes for everyone. Static elements are useful because they allow all instances of the class to use the same data, thereby saving memory.

-1
source

Here's a pretty common use case for static class variables:

 public class Foo { private static Dictionary<string, Foo> Foos = new Dictionary<string, Foo>(); public static Foo Create(string key) { if (Foos.ContainsKey(key)) return Foos[key]; Foos.Add(key, new Foo(key)); } public string Key { get; set; } private Foo(string key) { Key = key; } } 

Hiding the constructor and collection allows the class itself to reserve all the Foo objects created by the application.

-1
source

All Articles