static vs. instance variables

  • Thread starter Thread starter Aaron Irizarry
  • Start date Start date
A

Aaron Irizarry

When should I use static variables and when should I use instance variables?
I'm working on a class X and initially (for some reason I yet do not know),
I declared some variables static but the methods weren't. So I'd initialize
fill the variables statically and then I'd create an instance of X to work
on those static variables. Is there some reason why I should declare them
static?

Thanks.
 
Static variables/methods are "shared" by all instances of a class. For
example:

static int hey;

public void sethey(int value)
{
hey = value;
}

if this was enclosed in a class and several instances were initialized then
calling the sethey method in one of the instances would affect the value of
hey in the other instances as well.
 
it's crucial to use the right terminology. static members belong
to the type. in fact, instances DO NOT have access to static
members, which can only be accessed through the Type itself.

For the most part correct, but from within the class itself you don't
have to reference it through the type - this is assumed. For example:

namespace Y
{
public class X
{
public static bool Done = false;
public void SetDone()
{
Done = true;
}

override public string ToString()
{
return Done.ToString();
}
}

public class MyClass
{
public static bool Done = false;

public static void Main()
{
X mx;

mx = new X();
mx.SetDone();
Console.WriteLine(mx.ToString());
Console.ReadLine();
}
}
}


outputs 'True', even though X.SetDone() doesn't directly reference the
'Done' variable as 'X.Done'.

-mdb
 
Static variables belong to the class. There location is available as
slong as the class is referenced.

Instance variables belong to the instances of the class.

with regards,


J.V.Ravichandran
- http://www.geocities.com/
jvravichandran
- http://www.411asp.net/func/search?
qry=Ravichandran+J.V.&cob=aspnetpro
- http://www.southasianoutlook.com
- http://www.MSDNAA.Net
- http://www.csharphelp.com
- http://www.poetry.com/Publications/
display.asp?ID=P3966388&BN=999&PN=2
- Or, just search on "J.V.Ravichandran"
at http://www.Google.com
 
"Static variables/methods are "shared" by all instances of a class"

Correction. Static members belong to the class not to the instances. You
can access a static member only with the class name and not with the
instance of the class.

Class1.staticMember=1;

and not

Class1 ob=new Class1();
ob.staticMember=1; // Error

with regards,


J.V.Ravichandran
- http://www.geocities.com/
jvravichandran
- http://www.411asp.net/func/search?
qry=Ravichandran+J.V.&cob=aspnetpro
- http://www.southasianoutlook.com
- http://www.MSDNAA.Net
- http://www.csharphelp.com
- http://www.poetry.com/Publications/
display.asp?ID=P3966388&BN=999&PN=2
- Or, just search on "J.V.Ravichandran"
at http://www.Google.com
 
Back
Top