- Home /
When should i use static functions?
Hi, can anyone explain it to me why and when should i use static-functions? Thx
Answer by runevision · Dec 23, 2009 at 10:21 AM
Static functions enable you to call code without an instance of the class in which it's defined.
You cannot use instance data in a static function.
Normally, a static function should be self-contained. I.e. it should perform its function without requiring or saving any stateful data. A classic static function would be something like this (C#):
// MyClass.cs (C#): public class MyClass { public static float Multiply (float a, float b) { return a*b; } }
// MyClass.js (Javascript): static function Multiply (float a, float b) : float { return a*b; }
You can then call this function directly on MyClass without requiring an instance object of MyClass:
product = MyClass.Multiply(3, 2);
There are some different use cases though, where static functions do alter state that is saved in static variables. One example of this is the singleton programming pattern.
There are no "rules" for when to use static functions. You simply need to understand what it is and how it works, and determine for yourself in each situation if a static function is a good solution for the problem at hand.
I'm still not certain what constitutes stateful and stateless data. Is the transform of an object considered stateful?
@ina we usually say raw HTTP, for instance, is stateless because each HTTP request keeps no information about the last request. Stateful is the opposite. It basically means: one which is stateful is able to keep data stored to be used out of its own scope, and/or able to retrieve it.
Answer by rakeshparihar · May 17, 2017 at 07:24 AM
Check this link for your complete answer...... http://rakeshparihar.weebly.com/my-blog/static-keyword
Your answer
Follow this Question
Related Questions
Data from a simple singleton / static class return null 1 Answer
Can read but cannot pass variables between scripts... 1 Answer
Static variables assigned in the inspector 2 Answers
Static Variable crashes when accessed too fast? 0 Answers
Trying to create a static class for WWW-based functions and such 0 Answers