- Home /
General programming question on Static Classes
Hello this is not anything related to unity, just a general programming question
I am having a this doubt about the static classes and static function, still im unable to find which of the following is better at which situation.
say there are 2 classes,
public class A
{
public static void doSomething()
{
//
}
}
public static class B
{
public static void doSomething()
{
//
}
}
now if i call A.doSomething() and B.doSomething, what will be the difference, which one will be faster. And which one will be effective. Well is there any difference at all actually?
I have tried to figure it out for quiet some time now, but helpless here.
Answer by whydoidoit · Jun 13, 2012 at 10:10 AM
There is no difference in performance. A static class declares that all of its members are static, and the compiler enforces that.
The one benefit of static classes is that you can use them to write Extension Methods.
public static class A
{
public static void CoolHuh(this GameObject go)
{
go.transform.forward = go.transform.right;
Debug.Log("Not actually that cool");
}
}
Then you can do
anyGameObject.CoolHuh();
hey thanks a lot and also thanks for introducing me to extension methods, that is what i actually wanted to do.
and one more thing, isnt the static class loaded to the memmory as soon as the namespace is included?? then what about a normal class with all static methods? even that is the same??
They behave exactly the same. Even a normal class can have an additional static constructor and static variables which are initialized when you access the class the first time. There's really no difference except that the compiler forces you to make everything static.
Are you sure about that? I'm pretty sure the static constructor of a normal class that has no instance created is not called.
Given that the other comments may be hidden, I should just clarify that this comment was made before an edit of Bunny's reply above
Yes, i'm sorry, the static field initializer and the static constructor are called when ever you access any thing of that class. If you read a static variable for example the system will call the field initializers first and then the static constructor if the class hasn't beed already initialized ;)
I've changed my comment above
Your answer
Follow this Question
Related Questions
Are .gameObject and .transform both using GetComponent() in the background? 1 Answer
Add 2d rigidbodies to moving objects to increase performance or not? 1 Answer
Couroutines not working in static class 1 Answer
Increase Unity2D editor performance 0 Answers
(2 hidden skinned meshes) or (1 extra draw call) for character props? 2 Answers