Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
What is the difference between these declarations?
C#
static int Number=10;

int Number=10;
Posted
Updated 1-Feb-11 18:39pm
v2
Comments
JF2015 2-Feb-11 0:39am    
Fixed code formatting.
shakil0304003 2-Feb-11 4:28am    
Use google 1st!!!

1 solution

First declaration is static. This is just one physical object in the whole application domain.
If it is declared in some class; and the class has many instances, this field will be only one, accessible from any instance of a class itself. Same thing about structure.

Second declaration can mean different things. If can be a local variable, then it only exist on stack, accessible only withing the method where the variable is declared.

It also can mean instance variable of the class or a structure. If you created two instances of the same class or structure, there will be two different physical instances of Number. One instance can have Number==2, another one — Number==132, for example.

Let's see:
C#
class MyClass {
    internal MyClass(int number) {
        this.Number = number;
        StaticNumber = number * 2;
    }
    int Number;
    internal static int StaticNumber;
}
MyClass first = new MyClass(1);
MyClass copy = first;
MyClass second = new MyClass(2);

//now copy.Number == 1, because class is reference type
//first.Number == 1;
//second.Number == 2;
//MyClass.Number == 4, because it was done so by the last assignment


For future: please read C# manual before asking questions like that (and also — before programming :-) ). There is no sense to try before you learn such most basic things.

—SA
 
Share this answer
 
v3
Comments
JF2015 2-Feb-11 0:39am    
Good answer.
Christy A C 2-Feb-11 0:50am    
ok thanks
Pravin Patil, Mumbai 2-Feb-11 0:51am    
Nice answer.
Rahul Jain, Serious Coder 2-Feb-11 1:01am    
Great answer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900