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
2  
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
add comment

3 Answers

up vote 8 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
add comment

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
add comment

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
add comment

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.