tags:

views:

887

answers:

7

First of all, the static keyword.

I've read several articles and past threads on here covering the static keyword. I haven't found many scenarios listed of when I should use it. All I know is it doesn't create an object on the heap which tells me it would be good from a performance point of view for an object used a lot.

Is there any other reason to use it?

Also, I have read something about the static keyword and how it shouldn't be used with instance variables or to alter state. Can someone clarify this? It seems like this is a case of 2+2 but I can't get an answer (missing a few fundamental and simple pieces of knowledge).

Lastly, on the topic of thread safety, what should I look for in my code to get an idea of thread safety?

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

Thanks

A: 

Actually static variables are NOT on the stack, they're kept in a special segment of memory that's neither the stack nor the heap. Also, whether a variable is on the heap or the stack will have no affect on performance whatsoever.

Static function variables are variables that exist in a function and if changed retain their value between calls. They can be thought of as global values that are initialized on demand and can only be used in the function where they're declared. IMO there's really no good reason to use static variables in a function, other than for the occasional bit of testing.

Static member variables are variables shared between all instances of a class. So if your "Person" has a static member named "mCountry" then all people will share that variable. If one person changes it, it changes for everyone. Static members are useful as it allows all instances of a class to share the same data, thus saving memory.

Andrew Grant
I actually meant a special section on the heap (high frequency heap according to an article). Guess I'll have to check up on this. Also, you say retain their value and only used in the function they're declared - this sounds like a constant/readonly value with tight scope.
dotnetdev
Static variables are mutable and can be changed. So if you had a function with a static "count" value you could increment it everytime
Andrew Grant
I've found a few good articles on this issue. Really as a static field for example is like one data placeholder throughout the data, it would be good for something like application version. You don't want more than one of these. You would set it as static and change it, but have 1 instance.
dotnetdev
To help me understand, why are utility classes set as static?
dotnetdev
A: 

If you want to store something which is unique per instance, it should be an instance variable. You can make other data as static, if you think it is not unique per instance (or does not require creating an instance).

e.g. String.Empty (which is a public static readonly variable). Using this doesn't require you to create a new instance of string.

shahkalpesh
A: 

I use static variables to hold values (like sql querys) that are read from files, in functions that are going to be called alot (like in a loop). Avoids hitting the disk every time the function is called and is a good use of "information hiding".

Booji Boy
+3  A: 

The static keyword means something different in C, but in C# and Java it declares methods and variables to be of the class rather than an object.

You would want to use it for methods and variables that don't need any data from a particular object, but use the same data for each object of that type.

For example String.Format() is a static method of the String class. You call it in your code without creating a String instance. Likewise, Math.Pi would be a class variable.

But something like a length method doesn't make any sense unless it acts upon a specific instance of a string, so it would have to be an instance method. E.g., x = "hello".Length();

So if you want your method to be called with just the class name and not on an object, then you make a static method. Note that such a method can only reference static variables and call static methods, as it doesn't have an object with which to reference non-static members.

In C, the static keyword denotes file scope linkage. A top-level static variable or function does not get its name exported to other compiled object code. So two files can declare static variables of the same name and not create a conflict. We don't have this problem in C#, because there are namespaces, and private, protected, and public keywords to denote visibility.

Yet another meaning is for static variables within a function in C. These variables retain their value between calls to the function. For example, you could use one to count the number of times the function has been called. Static variables in C# also have this property, but you don't declare them within the method as in C, just within the class.

UncleO
I see. So if I want to manipulate a particular variable, use an as instance variable. Otherwise static as no data required.
dotnetdev
no, static on methods should be used when you either want global state or need no state directly. static in a state free context is a good thing in general since it makes a function more stable/usable
ShuggyCoUk
What does "need no state" mean? What is state exactly? Also, if I edit a string (string s = "sjsjs".Substring()), I could use an instance method with a parameter or a static method with a parameter. What's the difference?
dotnetdev
A: 

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 the collection allows the class itself to broker all Foo objects created by the application.

Robert Rossney
A: 

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

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

dotnetdev
A: 

Lastly, on the topic of thread safety, what should I look for in my code to get an idea of thread safety?

Writing thread-safe code is a hefty topic that I won't go into here, but I will say one thing on the topic of static & thread safety.

Most methods of ensuring code runs as intended for multiple calling threads involve some kind of locking on an object instance. You will notice that in the .NET framework (BCL), all static members are threadsafe. This is because there is no clear way of knowing what instance of an object ought to be locked on in order to share this resource between all conceivable callers.

Old guidelines used to suggest locking on the type itself, ie:

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

This approach is now discouraged and is inadvisable because there is no way of controlling the order of accesses to these lock objects across all conceivable calling threads. Locking on public objects (including ICollection.SyncRoot, which is now deprecated for the same reason) is opening the door to deadlocks. In the case above, the type instance is publically available, and should not be locked upon.

Given that there is no single instance that all clients of static methods can reasonably agree upon using for their access of static members, Microsoft's BCL team has had to make all static members typesafe. Thankfully for them, static members are few and far between.

Drew Noakes