First of all, the static keyword.
I’ve read several articles and past threads on here covering the static keyword. I haven’t found many scenarios listed of when I should use it. All I know is it doesn’t create an object on the heap which tells me it would be good from a performance point of view for an object used a lot.
Is there any other reason to use it?
Also, I have read something about the static keyword and how it shouldn’t be used with instance variables or to alter state. Can someone clarify this? It seems like this is a case of 2+2 but I can’t get an answer (missing a few fundamental and simple pieces of knowledge).
Lastly, on the topic of thread safety, what should I look for in my code to get an idea of thread safety?
I have posted this in VB.NET too because I don’t think different languages (C#/VB.NET) will have different rules.
Thanks
The static keyword means something different in C, but in C# and Java it declares methods and variables to be of the class rather than an object.
You would want to use it for methods and variables that don’t need any data from a particular object, but use the same data for each object of that type.
For example String.Format() is a static method of the String class. You call it in your code without creating a String instance. Likewise, Math.Pi would be a class variable.
But something like a length method doesn’t make any sense unless it acts upon a specific instance of a string, so it would have to be an instance method. E.g., x = ‘hello’.Length();
So if you want your method to be called with just the class name and not on an object, then you make a static method. Note that such a method can only reference static variables and call static methods, as it doesn’t have an object with which to reference non-static members.
In C, the static keyword denotes file scope linkage. A top-level static variable or function does not get its name exported to other compiled object code. So two files can declare static variables of the same name and not create a conflict. We don’t have this problem in C#, because there are namespaces, and private, protected, and public keywords to denote visibility.
Yet another meaning is for static variables within a function in C. These variables retain their value between calls to the function. For example, you could use one to count the number of times the function has been called. Static variables in C# also have this property, but you don’t declare them within the method as in C, just within the class.