So, what do you wanna know?
A field declared with the static modifier is called a static variable.
Static variables - if they are marked as public they are accessed without a class reference.
For intance:

class class1
{
    public static string myVar = "abc";
}

class class2
{
     public class2
     {
         string myVar2 = class1.myVar;
     }
}

What else would you like to know?

A static variable is one that doesn't require an instance of the class to access.
A static method is one that doesn't require an instance of the class to access.

public class MyClass {
    static public int myStaticInt = 3;
    public int myNonstaticInt = 5;

    static public void MyStaticMethod() {
        Console.WriteLine(myStaticInt);
        Console.WriteLine(myNonstaticInt);  // Error! Need an instance of the class!
    }

    public void MyNonstaticMethod() {
        Console.WriteLine(myStaticInt);
        Console.WriteLine(myNonstaticInt);
    }
}

I do not the understand the Code . And what is use of this code "Console.WriteLine(StaticExample.ivar.ToString();

class Program
    {
        static void Main(string[] args)
        {
            StaticExample.ivar = 1;
            Console.WriteLine(StaticExample.ivar.ToString());
            Console.ReadLine();

        }
    }
    public class StaticExample
    {
        public static int ivar;
    }

Edited 5 Years Ago by Ezzaral: Added code tags. Please use them to format any code that you post.

If you want to access some non-static member inside some class FROM a static method, you need an instance of that class:

class Program
{
    private int myFiled = 1;

    static void Main(string[] args)
    {
       //You can NOT do:
       int a = myField; //myField is not accessible!!
 
       //what you have to do, is to create a new reference of the class the variable is in:
       //so:
       Program p = new Program();
       int b = p.myField; //this is OK!!
    }

     //for example, if you have a non-static class:
     private void MyMethod()
     {
          //you can access to class`s members:
          int c = myField; //this is OK!!
     }
}

The same you do if the field (or some other member) needs to be accessed in some other class.

Hope this is clear enough how to access static members. The bottom line is, that you canNOT access to class members outside of the static class WITHOUT an instance of a class (in our case, an instance is p).

This article has been dead for over six months. Start a new discussion instead.