Static Methods and ability to access variables

18,163

the static keyword from MSDN:

A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created. Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.

It is more typical to declare a non-static class with some static members, than to declare an entire class as static. Two common uses of static fields are to keep a count of the number of objects that have been instantiated, or to store a value that must be shared among all instances. Static methods can be overloaded but not overridden, because they belong to the class, and not to any instance of the class. Although a field cannot be declared as static const, a const field is essentially static in its behavior. It belongs to the type, not to instances of the type. Therefore, const fields can be accessed by using the same ClassName.MemberName notation that is used for static fields. No object instance is required.

C# does not support static local variables (variables that are declared in method scope).

Static means that it can be accessed directly against an object without creating an instance, i.e a class, so a static member Name defined in class MyClassName can be accessed like so: MyClassName.Name(instead of new MyClassName().Name), and when you access a static member from inside that class, you can just use Name but the compiler is treating similar to you would be accessing it from outside the class.

While a static value is unchanged, any people who call that static property in an application are accessing the same instance, which can lead to concurrency issues if the value can be changed from outside the class.

Take the following example:

public class MyClassName
{
    public static string FilePath = @"C:\Temp";
    public static FileStream fs;

    public static void CreateFileStream()
    {
        //creates a file stream
    }
}

If two people call the same method at the same time, MyClassName.CreateFileStream() then the one who gets in there first creates a file stream and sets it to fs, then the second person creates a file stream and sets it to fs, now it is possible that someone has a reference to the file stream in the class, and the other one could be holding on to a reference to the original file stream that is no longer set on the class MyClassName.

As such you will want to pay mind to how you expose static members (not an issue in your specific example, but important to keep in mind). If you declare a static field, you should be sure to instantiate it or keep it private to the class so you can be sure it is instantiated be for using it.

In your case you are creating a new file stream every time you call that method because your bool fileopen is inside the method, anything inside of a method is only available inside that method, regardless of being static or not, and is created again every time that method is called, and you need to use the static keyword on every declaration of a field or property or method that you want to call from another static field, property, or method.

class Program {
    static FileStream fs;      //needs to be static
    public static bool fileopen = false;    //needs to be static
    static  String filename = @"D:\Stock Trading\Test1.txt"; 
             //needs to be static, or this one could also be 
             //const if it will never change

    static void Main(string[] args) {
        CreateDebugFile();
    }

public static void CreateDebugFile() {
    //...
    }
}
Share:
18,163
rwbil
Author by

rwbil

Updated on June 04, 2022

Comments

  • rwbil
    rwbil about 2 years

    I am trying to access variables from a static Method. I understand the basic concept of static vs non static methods, but still do not fully understand what a static method can and cannot access.

    At first I tried to put my variables at the top in the Program Class as you can see from some of my commented out lines. I could not access them from my static method which as I learned more about static made sense. But then I put the variables inside the static method. And this is what I do not understand. Inside the static method I can set fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite); yet once outside the if statement the sw = new StreamWriter(fs) gave me an error when I had FileStream fs inside the static method. Tried making it static as you can see by the commented out line inside the static method but that does not work either. The only way I seem to be able to access my variables is if I make them static inside the Program class (outside the static method).

    class Program {
        static FileStream fs;
        //   public bool fileopen = false;
        //  String filename = @"D:\Stock Trading\Test1.txt";
        static void Main(string[] args) {
            CreateDebugFile();
        }
    
        public static void CreateDebugFile() {
            StreamWriter sw;
            bool fileopen = false;
            //      static FileStream fs;
            String filename = @
            "D:\Stock Trading\Test1.txt";
    
            if (!fileopen) {
                fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
                fileopen = true;
            }
    
            sw = new StreamWriter(fs);
            sw.Write("Current Bar" + "\t" + "time" + "\t" + "Open" + "\t" + "Close" + "\t" + "Low" + "\t" + "High");
    
        }
    }