0

Im having difficulty with static methods vs non static, I think I understand the concepts but not when or why I would each. So far I have

If the class has properties and I want to store data as a type I need to make an new instance.

Static methods are shared in some way across the program as a whole but does this mean there is a danger of data being shared?

If I have a method that preforms actions only on the data passed in and returns it, it should be static right

DarkBee
  • 16,592
  • 6
  • 46
  • 58
CerIs
  • 527
  • 3
  • 6
  • 14
  • 2
    If a method is static, there is no data to share (there is no `this`). – SLaks Oct 05 '16 at 21:18
  • Try searching through the new documentation (http://stackoverflow.com/documentation/c%23/topics) to see if this can narrow you down to a more specific question. –  Oct 05 '16 at 21:22
  • 1
    It can be static but not obligatory. It depends on calling places - if they will be in other classes, then make it static. – i486 Oct 05 '16 at 21:24
  • If you have a class containing only "pure functions", which work based only on passed parameters and no "hidden state" in the class or anywhere else, then static is a good idea but not a requirement. Static methods are slightly faster at runtime, and don't require instantiating an instance of your class (which will use a little extra memory even if there are no instance members). – KeithS Oct 05 '16 at 21:29
  • @i486 Whether or not something is static has nothing to do with what calls it, but rather whether or not the operation's a) has state and b) whether the scope of that state ought to be per instance. That has nothing to do with where the code is called from. – Servy Oct 05 '16 at 21:30
  • @Servy Public static _method_ (not object) can be called from any class (method) without need of corresponding object. It is like global method. – i486 Oct 05 '16 at 21:34
  • @i486 Yes, and a public instance method can *also* be called from any class, so whether the method is static or not has nothing to do with were it is called from (the accessibility is what cares about that) but rather whether the method depends on state of a given instance. If the method needs to access state of an instance, it needs to be an instance method, if it doesn't (and doesn't need to leverage virtual dispatch), it's conceptually static. – Servy Oct 05 '16 at 21:36
  • @Servy can you expand on "state of an instance"? – CerIs Oct 05 '16 at 21:37

0 Answers0