Reputation: 2133
After a few years of C++, I'm diving into a different language (C#) with Unity. I'm doing my first class assignment. My professor has some variables declared as private, but she is initializing them instantly upon declaration. In C++, we wouldn't never initialize a private data member in the private block, but in a constructor. From what I read, we are not to use constructors in classes that are derived from MonoBehaviour
. So my question is:
Is it ok to initialize the private objects (Strings, ints, etc.) in upon declaration in a class in C#? Or is this something we shouldn't do, like in C++, and they should be initialized elsewhere?
Upvotes: 1
Views: 3468
Reputation: 321
I don't thing there is a straight answer to your question, rather good practices.
First thing first, C# automatically give a default value to common types (int > 0, char > 0 ('\0'), float 0.0f, null for a reference type, ...) so you do not need to initialise those unless you've a specific behaviour which involves a specific initial value (like, giving maximum value to an int intended for a function returning a min value). This property extends to structures (a struct containing an int and a string will automatically be initialized to 0 and null for those fields).
For reference types, and on a general manner, anything which requires custom allocation/initialisation, I usually do all of that, if possible, in constructor because, eh, that's what they are made for, making your object ready to use for extern users.
In case of Unity, initializing should also be good in Start().
Your professor way is of course acceptable. Some more piece of information : Initialization - Stack Overflow
Upvotes: 2
Reputation: 23
Yeah it's really okay, but it's also possible to initialize it in the Start() method if they implements MonoBehaviour
Upvotes: 1