none
What is the difference between Public variable and static variable in c#

    Question

  • What is the difference between public and static variable declaration in c#.

     public partial class FrmDisplayTest : Form
        { 
          public static string Webpath = "";
          //and
          public string Webpath = "";
        }

    Thanks in advance.


    Experience the innovation with perfection.

    Thursday, January 17, 2013 11:49 AM

Answers

  • Basically static variables are stored in Stack memory in RAM & other types of variables are stored in initialized and uninitialized and heap  memory in RAM.

    This isn't really true. The static variables will be on the stack, but the objects they point to (if they're reference types) will not be on the stack. All local variables will be on the stack, and all fields of a type will go where that type is stored, which means the heap for a reference type and either the stack, heap, or another location for a value type.

    Having said all of that; this is merely an implementation detail that is not particularly relevant to know.

    • Marked as answer by Bhagawat Friday, January 18, 2013 5:43 AM
    Thursday, January 17, 2013 4:02 PM

All replies

  • public string Webpath;

    will require that the class be instantiated, something like:

    FrmDisplayTest l_form = new FrmDisplayTest();
    l_form.WebPath = "something";

    and applies to a single instance of the class, whereas

    public static string Webpath;

    does not

    FrmDisplayTest.WebPath = "something";
    and applies to all instances of a class.

    It would be greatly appreciated if you would mark any helpful entries as helpful and if the entry answers your question, please mark it with the Answer link.


    Thursday, January 17, 2013 11:59 AM
  • Hello,

    Changes done to static (or shared) members are scoped to the to class whereas in instance (or nonstatic) members changes are unique to the particular instance of the class.


    Regards,

    Eyal Shilony

    Thursday, January 17, 2013 12:21 PM
  • Static variables can be accessed across all objects. While Public variable can be accessed only in that object. For example

    //Initializing static variable
    FrmDisplayTest.Webpath = "http://msn.com";
    
    FrmDisplayTest object1 = new FrmDisplayTest();
    //Init object1's public variable
    object1.Webpath = "Obj1";
    //Now here if you try to access the static variable
    //FrmDisplayTest.Webpath
    //This will give you http://msn.com
    
    FrmDisplayTest object2 = new FrmDisplayTest();
    //Init object2's public variable
    object2.Webpath = "Obj2";
    //Now here if you try to access the static variable
    //FrmDisplayTest.Webpath
    //This will give you http://msn.com
    
    


    A.m.a.L Hashim
    Microsoft Most Valuable Professional
    My Blog - Dot Net Goodies

    Thursday, January 17, 2013 12:32 PM
  • Hi,

    Public is a access specifier that indicates the member will be accessable outside the class code also.

    There are other access specifier like private , protected , internal , protected internal. All have different meaning and special usages.

    static keyword in C#(Shared in VB.NET) allowes to access that member even without creating object of that class.

    In your code first Webpath is static so that member can be accessed just by using the class name like :

    FrmDisplayTest.Webpath

    On the other hand your second Webpath variable is not static, so that member will come into existance when object of the class is creaed and using that object reference you can access that second Webpath member.

    public and static are not in any way related to each other.

    For more information please visit these links :

    static (C# Reference)

    Access Modifiers (C# Reference)

    Let me know if you have any more confusion.


    One good question is equivalent to ten best answers.



    Thursday, January 17, 2013 12:36 PM
  • To add to discussion:

    Anything marked PUBLIC means that any other class using this class can see and use these variables.  It applies to Static and non-Static variables.  Look at Public variables and methods as how others can use this class.  PUBLIC variables can have PRIVATE (backing store) variables that hold the values the program wants the public to see.  This is called data hiding.  Data Hiding is the safe way to expose PULIC variables but to only allow them to see what the class wants them to see.  Data Hiding is an important concept in OOP and OOD discussions.

    STATIC is a keyword in C# which has very unique effect.  At runtime, the CLR (Common Language Runtime) does things in a very specific order.  One of the first things done, is to initialize STATIC varialbes.  This then, allows two very distinct different aspects of a  class: The STATIC side of things and the NON-STATIC side of things.  The designers of .NET knew these two sides very well, as we can find, for example; all PROPERTIES of a class without instanciating the class.   This is a very subtle but important concept that has very profound effect.  As you learn more about these two sides, you, like me will always look at classes as having two very profoundly different aspects with two very different purposes in mind.  What are those purposes?

    In OOP and OOD there's a lot of talk about the Factory pattern. When a method is Static it means you can always call it without an instance of the class! This gives rise to the very nice Factory pattern which looks like this:

    var t = Task.Factory.StartNew(()...);

    We also see this same Factory like concept being applied to the newer Extension method support.  Extension methods are static classes combined with static methods!

    As already mentioned we can get all properties of a non-instanciated class:

    //note the return type is a WidthProperty not the Width
    var widthProperty = Button.WidthProperty

    Static varialbes can act as a pre-determined constant of the non-static variables to work with once the class is instanciated:

    private static int BaseWidth = 10;
    public Rectangle GetRectangle(){
       //the value of BaseWidth is always created before the class is so this value will always be there before using it.
      return new Rectangle(BaseWidth, 2 * BaseWidth);
    }

    Static variables are often used for Delegates, Actions and Func (Functions).. Why? Because we may want to have an entry into code before we know which instance is being used! 

    public class MyClass{
    public static Action<String> MyAction;
    public static Event MyAction ItsEvent;
    
    //in the CTOR logic of this class hook up the Action
    
    public MyClass(){
    }
    public void DoWork(){
       //do something to get proper string here 
       //Are there any listeners out there?
       if(ItsEvent != null){
            //There is one or more listeners send the message
            ItsEvent("Somestring");
       }  
    }
    }
    
    
    //the code above allows us to do this in one or more classes
    
    MyClass.ItsEvent += MyEventHandler;
    
    //this is very subtlely different than this:
    MyClassInstance.ItsEvent += MyEventHandler


    JP Cowboy Coders Unite!



    Thursday, January 17, 2013 12:56 PM
  • Hi Hashim,

    I am just wondering a little bit - maybe you meant the correct but I would never say it that words.

    A static variable cannot be accessed through objects of the class!

        public class Test
        {
            public static string TestString = "Test!";
    
            public void TestMethod()
            {
                TestString = "otto"; // Compiles
                Test aTest = new Test();
                aTest.TestString = "Test"; // Does not compile!
            }
        }

    If you try the above you will see that creating an instance of an class and then access a static variable through the object simply gives you the error: Member '<NamespaceName>.<Classname>.<Membername>' cannot be accessed with an instance reference; qualify it with a type name instead

    With kind regards,

    Konrad

    Thursday, January 17, 2013 1:01 PM
  • Very good point Konrad and even more ammunition to think in terms of any class as having two very distinct attributions, the Static side of life and the non-static side.  It's almost like two totally different worlds...

    This would compile however:

      public class Test
        {
            public static string TestString = "Test!";
    
            public void TestMethod()
            {
                TestString = "otto"; // Compiles
                Test aTest = new Test();
                Test.TestString = "SomeTest"; // Does compile!
            }
        }


    JP Cowboy Coders Unite!


    Thursday, January 17, 2013 1:07 PM
  • Hi,

    you got a lot of nice replies already. I always like to think where the memory of the variable could be found.

    - A non static variable is placed inside the instance of a class.

    - A static variable is places inside the class / type.

    Or to give a real world comparison:

    The class is a plan on how to build something. A static variable would be something that is written on the plan.

    A non static variable is something that is build with the plan.

    So the typical car example: A class could be a plan how to build a specific car. On the plan we make a small sign for each car that we create. (= static variable)

    The cars you build have a trunk in which you could put something (= non static variable). So if you have 2 cars of the same plan: If you put something inside the trunk of car1 then the trunk of car2 stays unchanged.

    Konrad

    Thursday, January 17, 2013 1:14 PM
  • Hmm ... I do not fully understand that. I always like the book about smalltalk because in smalltalk you just have objects. In .Net it is more or less like that but there are a vew differences.

    So the class is just some kind of source which is compiled to an assembly. When an assembly is loaded, objects are created. So from your class you get a Type object. The static variable is more or less simply a variable inside that type now.

    The non static variables are part of the instances so you need an instance.

    That is my personal view on it in which I only think of objects. But the types are also just some plain objects for me.

    With kind regards,

    Konrad

    Thursday, January 17, 2013 1:22 PM
  • For accessing the static variable, we do not need to instantiate the class. The static variable scope is on class level. But public variable  will be accessible via an instance of a class. This is same for method as well. There in some time we declare private method as static. The reason is static method call emit nonvirtual call instruction in msil, that will gain the performance.



    Thursday, January 17, 2013 2:31 PM
  • Data Hiding is the safe way to expose PULIC variables but to only allow them to see what the class wants them to see.  Data Hiding is an important concept in OOP and OOD discussions.

    Data or Information Hiding has a much broader meaning.

    The principle advices you to hide anything out of your clients that they shouldn't know.

    In OOD - SOLID You can find the Interface Segregation principle that is a subset of the Information Hiding principle which advices you to abstract away or group together functionality into various interfaces so each client will see only the things it expects.

    In OOP, this principle is applied through Encapsulation that is one of the three principles that defines an OOP language that suggests it will have the tools to bring this principle into practice in the language itself.

    Infromation Hiding is important in OOP languages because of the above point but it doesn't tell you anything about the implementation per se because it has nothing to do with it.


    Regards,

    Eyal Shilony

    Thursday, January 17, 2013 3:42 PM
  • Basically static variables are stored in Stack memory in RAM & other types of variables are stored in initialized and uninitialized and heap  memory in RAM.So static variable share same memory location for all the objects of the same class.  but in ordinary variable declaration, memory will be occupied by the variable will be different locations(means individual memory space).
    Thursday, January 17, 2013 3:44 PM
  • Basically static variables are stored in Stack memory in RAM & other types of variables are stored in initialized and uninitialized and heap  memory in RAM.

    This isn't really true. The static variables will be on the stack, but the objects they point to (if they're reference types) will not be on the stack. All local variables will be on the stack, and all fields of a type will go where that type is stored, which means the heap for a reference type and either the stack, heap, or another location for a value type.

    Having said all of that; this is merely an implementation detail that is not particularly relevant to know.

    • Marked as answer by Bhagawat Friday, January 18, 2013 5:43 AM
    Thursday, January 17, 2013 4:02 PM
  • @All thanks guys ...... wonderful help

    Experience the innovation with perfection.

    Friday, January 18, 2013 5:43 AM
  • The static variables will be on the stack

    Static variables on the stack? Only local variables go on the stack. And local variables cannot be static in C#. And I don't expect languages which allow that to put them on the stack either.
    Monday, January 21, 2013 8:39 AM
  • Static variables on the stack? Only local variables go on the stack. And local variables cannot be static in C#. And I don't expect languages which allow that to put them on the stack either.

    Well, they potentially could be at the top of the stack given that their size is known and they never leave scope.  Upon a bit of looking around, there's a separate storage location specifically for them.
    Monday, January 21, 2013 3:14 PM
  • Well, they potentially could be at the top of the stack given that their size is known and they never leave scope.
    That would mean they are specific to a thread AND that they are all known at the start of the program.
    Monday, January 21, 2013 4:37 PM