30

I'm new to c sharp and programming generally. I have a quick question - what is best practise with regards to static/non static variables.

I have a variable,private int x, which belongs to class y. To access this variable, i need to reference y. If x was static however, i can access this variable with no references to y.

Which is the best way to go, in a situation whereby several methods within the class y will be referencing this value ?

Hope this makes sense, and my question isn't too basic !

Many thanks

1
  • 4
    The best way to go is the one which makes your code work as intended while being both very self-descriptive and easy to mantain. To clarify: there is no "right" answer to "what's best" when it comes to developing.
    – Alex
    Mar 29, 2012 at 11:26

7 Answers 7

58

You need to think about static variables as belonging to the class, not to instances of the class.

If, in all instances of the class this variable should be identical, use a static variable.

If not, use an instance variable.

In general having public static variables is bad practice - it is a shared global resource and if you change it you need to synchronize access to it. Having global state is something you want to avoid as much as possible.

0
12

Best practice is to avoid public static. In OOP, class is meant to hide its members. Static is actually not a member of the instance but of the type.

Static comes handy if you are implementing singleton pattern. But then again they need to be made private and accessible through a public property.

You need to read Static Classes and Static Class Members (C# Programming Guide).

5
  • This is new to me. Why should statics be avoided ?
    – Alex
    Mar 29, 2012 at 11:25
  • The answer is lengthy, not a typical Stackoverflow Question. Statics goes against OOP and SOLID principles.
    – Aliostad
    Mar 29, 2012 at 11:30
  • What about XAML Dependency Properties and/or extension methods and the like ? Am I missing something obvious here ?
    – Alex
    Mar 29, 2012 at 11:44
  • There are situations where statics can't be avioded (take for instance a public readonly static DateTime DefaultDate = ...;. Mutable static fields or readonly statics for mutable objects should be reviewed very carefully, since this is a source of multi-threaded bugs. So in general I agree with Aliostad.
    – Steven
    Mar 29, 2012 at 11:46
  • Steven: you hit it on the head! Mutable is not good but immutable fine. Alex: I said static variables and not methods. I love extension methods.
    – Aliostad
    Mar 29, 2012 at 12:09
5

Well I can't conclusively say that one is better, because they serve different purposes.

Are you familiar with OOP? In OOP, static objects or members of a class that can be accessed directly from the class, while non-static members can only be accessed from the instance it belongs to.

C# follows a similar principle for the methods. The static methods can by accessed directly from the class, while non-static methods (or instance methods as I like to call them) have to be accessed from an instance. That is why instatiating needs to be done for instance methods, while for static methods it's just not needed, and furthermore impractical (see below).

In OOP, static variables are used for values which cannot be stored by an instance variable. Example: supposed you wanted to keep a count of how many instances of a class exists? How would you store that in a single instance?

The methods use a similar principle. They should be used for procedures for which it is impractical to do within an instance of a class. I tend to use them for broad procedures (not a technical term), meaning those that do not require me to instantiate an object. Example, adding two parameters. (This usage may or may not be correct, but I believe it is)

However, if you wanted to add two properties of an object, the method cannot be static, because as you would soon realize, static methods cannot access instance methods or variables within a class. Of course that makes sense because that static method would not know which instance of the class the get these from unless it were told, since it is not part of an instance itself)

For the sake of no further complicating things, I'll stop here. Let me know if you misunderstood anything.

3

Your choice depends on your architecture.

Static makes part of a Type, others make part of an instance of that type. If you want have some shared state (say) between different instances of the same type, use static. If you want that every instance have it's own value, independent from others, use instance fields.

In both cases, by the way, avoid to expose like a public fields, but use properties.

1

I completely agree with Mr Oded:

If, in all instances of the class this variable should be identical, use a static variable.

If not, use an instance variable.

Yes, adding static to a class member basically means you can access it without an instance, and only outside any instance. And yes, it becomes a global resource, or even a global variable if you will.

But I think there's at least another (heavily edited) good point to be made here...

Using static members as global vars go against OOP

This means once you set a static member you can't pass it around as an object. The more you use static as global var, the more difficult it is for unit testing / mocking classes.

There is a solution for that, Singletons. But they should never come without warnings!

At other hand, if you're sure you really need global vars, take a look at the Toolbox pattern. It's a not well known extension of Singleton pattern. It's so unknown in fact, if you google for it you won't find it with those keywords (toolbox pattern).

So plan ahead. Read more. Get to know about every option so you can decide better. Even get a book. Object Oriented Programming is more about applying concepts that will help in the long run than just making things work now.

0
0

In general if you want to have a variable public, either static or instance, you must wrap it in a property and expose it like that. This is for sure a principle that you will love to follow.

But despite some of the other answers I cannot say don't use static. Static is not the devil that you should avoid in any case. What you have to do will decide if you are going to use static or not, as long as you keep your program clean and easy to maintain.

Easily speaking, and not in the language of the elders, static stands for something that don't belong to any instance of this class but has an effect on them. An example of a static property in a class that generates instances is for example a factor, which should be global for all instances of the class, to take part in a calculation that is done inside instances. To this case, and to my opinion, it is better to have this factor declared as static rather that have it in every single instance. Especially if this factor changes in the lifetime of your program to affect the next calculation.

0

You need to ask a question to youself: why I need x to be static?

If you make x static it means that x is a part of all objects of class A, but when x is not static it means, than x is a part only of one object.

In geleral using of static fields is painfull for bug tracking, but in some cases this is very helpfull.

I suggest you to look in using of singelton http://en.wikipedia.org/wiki/Singleton

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.