Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I have some experience in developing with Java, Javascript and PHP.

I am reading Microsoft Visual C# 2010 Step by Step which I feel it is a very good book on introducing you to the C# language.

I seem to be having problems in understanding the static keyword. From what I understand this far if a class is declared static all methods and variable have to be static. The main method always is a static method so in the class that the main method exists all variables and methods are declared static if you have to call them in the main method. Also I have noticed that in order to call a static method from another class you do not need to create an object of that you can use the class name.

What are the advantages of declaring static variables and methods?

When should I declare static variable and methods?

share|improve this question
3  
static in C# is almost the same as static in Java. If you understand it in Java, you mustn't have any problems in C# –  superM Sep 3 '12 at 10:16
    
Java was my first programming language and I did not understand this concept there either.I have only used Java for a short period of time –  Nistor Alexandru Sep 3 '12 at 10:16
    
In short: use "static" when you need no object orientation, for example, just some stand-alone methods or variables. Declaring a class to be static means to put those non-object oriented functions and variable just in a common name(space), the class name. –  Doc Brown Sep 4 '12 at 19:30

4 Answers 4

up vote 11 down vote accepted

The static keyword in C# is refering to something in the class, or the class itself, that is shared amongst all instances of the class. For example, a field that is marked as static can be accessed from all instances of that class through the class name.

public class SomeObject
{
    //Static Field
    static int Foo = 3;

    //instance field
    private int _Foo2 = 4;

    //instance property
    public int Foo2{get{return _Foo2;}set{_Foo2 = value;}}


    //static constructor
    public static SomeObject CreateSomeObject(int fooValue)
    {
        SomeObject retVal = new SomeObject();
        retVal.Foo2 = fooValue;
        return retVal;
    }

    //Parameterless instance constructor
    public SomeObject()
    {
    }

    public static int Add(int x)
    {
        //Static methods can only deal with local variables, or fields that
        //  are also static in the class.  This one adds x to the static member foo
        return x + Foo;

        //Foo2 is not accessable here!
    }

      //Instance method
    public void AddSomething(int x)
    {
        //Add x to the property value of Foo2
        return x + this.Foo2;

        //Note that Foo *is* accessable here as 'SomeObject.Foo'
    }

}

I can honestly say that I have never used a class marked as static with the exception of creating extention methods (Quick tutorial on extension methods).

Anyways, there are specific design patterns for utilizing static methods, such as factory pattern and singleton pattern, but the important thing to remember is that static methods and constructors do not deal with any specific instance of a class (unless you pass one in). So utilizing static methods is more of a stateless implementation of a methods, e.g. to do calculations or to do a comparison between objects. The "Main" method you are refering to is always static, but to see it from a different point of view, see this article.

To follow up with this, here is how the difference between static and instantiated methods, fields and properties are called.

public static void Main(string[] args)
{
    //This is a static method that starts a thread in an application
    // space.  At this point not everything actually has to be static...

    //Here is an instantiation with a parameterless contruction
    SomeObject obj = new SomeObject();

    //Here is an instantiation using a static contructor (factory)
    SomeObject obj2 = SomeObject.CreateSomeObject(3);

    //Getting field value from static field
    // Notice that this references the class name, not an instance
    int fooValue1 = SomeObject.Foo;

    //Getting property value from instance
    //  Note that this references an object instance
    int fooValue2 = obj2.Foo2;

    //Instance method must be called through an object
    obj2.AddSomething(4);  //if default constructor, would return 8

    //Static methods must be called through class name
    SomeObject.Add(4); //Returns 7
}

Also, check this post out for a deeper look into static classes.

share|improve this answer
    
@phant0m, Thanks for the edit, it wouldn't let me post my links, since I had no rep on this site! –  iMortalitySX Sep 4 '12 at 21:59

Here's Joshua Bloch's way of explaining it, which I find brilliant like most of what he says (yes I'm a Joshua Bloch fan boy :) ). This is quoted from memory.

Imagine that a class is the equivalent of a blue-print for a house. Image then that a house is to the blueprint as an instance of the class is for the class. You can have one class (blue-print) and multiple instances (houses) created from it.

Now common sense dictates that most of the functions/behaviors that a house (instance) can have/do, even though they are declared in the blue-print, cannot be used until an actual house (instance) is made out of that blue-print (class). Like, your blue print might contain in it the place where the light switches and the light bulbs should go, but you have no way of making those work on the blue-print, you have to actually build the house in order to be able to switch the light switch on and off and have certain light bulbs go on and off.

However, you might have some behavior that is applicable to the blue-print directly, and which you could use/access directly on the blue print without needing to make an actual house out of that blue print. Imagine that your blue-print has a button that, upon pressing, will display the footprint of the house contained in that blue print (by calculating all the lengths of the walls and such). Obviously you COULD build a house first, then go around measuring its footprint, but you can do this with he blue-print alone, so it would be more helpful to have this behavior implemented in the blue-print. Such a blue-print embedded button that calculates the footprint of the house is the equivalent of having a static function in a class.

share|improve this answer

Looking at it this way helps me:

  • Every type has a static instance.
  • The static instance is created at the first time you access the type -- either through the static instance or creating another instance.
  • You can create as many non-static instances as you like, but there is only one static instance.
  • Anything within a class that is declared as static belongs to the static instance, and thus doesn't have access to any other instances you create. But the other instances DO have access to the static instance.
  • If a class is declared as static then you cannot create other instances, only the static instance can ever exist.
  • You can declare a static constructor for the static instance just like a constructor for a normal instance (but by declaring it static).

As for when to use the static keyword:

  • Any method that doesn't need access to local properties can and probably should be declared static.
  • Helper classes that don't have any state whatsoever (which should be rare anyway) and that will never be mocked can be declared static. Whether they should is another matter; use this functionality sparingly.
  • Properties and fields that must be accessed by all instances of a class must be declared static. But use this only when there is no other option.
share|improve this answer
    
+1, for a good summary, I did not know that every type has 1 static instance and I find it strange to tell you the truth. –  Emmad Kareem Sep 3 '12 at 12:38
2  
@EmmadKareem That's just a mental model pdr uses, because "Looking at it this way helps" him. You find it strange because it's not exactly true, but you can think of it like that if you want. Do you know the Bohr model? It's a presents a set of rules and ideas how atoms and electrons interact with each other. The model works depending on what you do, but it is not the reality. –  phant0m Sep 4 '12 at 21:06
    
@phant0m, thanks for the explanation, I was under the impression that it was real not a model and I was surprised because of that. –  Emmad Kareem Sep 4 '12 at 21:10
    
Actually, there are sometimes reasons you might not want to make a method static even through is doesn't use local properties. Making things static can add coupling to clients because they have to address the class directly. For example, this can make it more difficult to unit test w/ mocking. –  Allan Nov 17 at 16:03
    
@Allan: Arguably, if you're calling a public method on a class that doesn't affect the state of an instance of that class, it SHOULD be static, to make that clear to the client developer. If that method does so much that it needs mocking, that's a different problem that can be solved a number of different ways. –  pdr Nov 18 at 11:55

The static keyword can be a little hard for newbies to grasp. Its primary purpose is to identify a class member as not belonging to any single instance of the class, but instead to the class itself.

Without going into too much detail, C# (and Java) rigidly enforce the object-oriented ideal that all code and data must belong to an object, and therefore is limited in scope, visibility and lifetime. That's generally best practice wherever the fundamental tenet of an object representing some real-world thing applies. However, it doesn't always; sometimes what you need is a function or variable that you can get to from anywhere in code, without requiring you to pass around a reference to an object containing it, and with the guarantee that the data you are looking at or changing is exactly what everyone else is dealing with, and not a copy of it belonging to a different instance of an object.

Such behavior was available in C and C++ in the form of the "global" function or variable, which was not encapsulated in an object. So, as a compromise, C# and Java support "static scope", a halfway point between truly global code with no parent object and limited-scope instance members.

Any "code member" (function, property, field) declared as static comes into scope as of the first line of the program's main() function, and does not leave it until the main() function terminates. In plain English, a static member exists and can be used as long as the program is running. In addition, static members are invoked by calling them as members of the type itself, not members of any one instance of that type:

public class Foo
{
   public int MyInt {get;set;} //this is an "instance member"
   public int MyStaticInt {get;set;} //this is a "static member"
}

...

var myFoo = new Foo();
myFoo.MyInt = 5; //valid
myFoo.MyStaticInt = 5; //invalid; MyStaticInt doesn't belong to any one Foo

Foo.MyInt = 5; //invalid; MyInt only has meaning in the context of an instance
Foo.MyStaticInt = 2; //valid

This makes static members visible to any code that has knowledge of the type, whether or not they know about any single instance of it.

To answer your question, the primary benefit of marking something as static is that it becomes visible wherever the type itself is known, regardless of whether the consuming code has or can get an instance of the containing object. There's also a slight performance benefit; because the method is in static scope, it can only access other static members (of the same class or others), and whatever is passed in as a parameter. Therefore, the runtime does not have to resolve any reference to the current instance of the containing object, as it normally would have to for an instance method in order to provide context-specific state information.

Entire classes can also be marked static; by doing so, you tell the compiler that the class declaration will consist solely of static members, and thus cannot be instantiated. This is an easy way to ensure there is one, and only one, copy of an object in memory; make the class and everything in it static. However, it's very rare that this is the best solution to such a need. In a situation where exactly one copy of a set of data is required, the "singleton" is typically advocated instead; this is a non-static class, which uses a static accessor and a non-public constructor to provide access to a single instance of itself. Theoretically, a singleton provides much the same benefits of a fully static class, but with the added ability to use the class in an instance-based, object-oriented way.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.