N
N
Noortvel2017-01-03 12:28:19
C++ / C#
Noortvel, 2017-01-03 12:28:19

Should I check for null in a getter?

Should I check for null in a getter?
Or is it better to initialize in Awake ()? Just then you will have to receive a variable for each class separately, where initialization in Awake () is needed.
Here is an example:

ExampleClass ec;

public ExampleClass GetExampleClass(){
    if(ec == null){
        ec = GetComponent<ExampleClass>();
    }
    return ec;

}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
GavriKos, 2017-01-03
@Noortvel

Quite a dumb question. It all depends on your internal logic. But - it looks ugly and smacks of design errors - first Init, which does everything GetComponent, and then outside the use of a getter.

M
MrDywar Pichugin, 2017-01-03
@Dywar

Better this way:
And this is only a question about initialization time, similar to Lazy.
If the object is definitely needed, then in Awake(), if there are many such objects and the requested property is not always needed, then it is possible and so, the difference in performance will be insignificant.

ExampleClass ec;
public ExampleClass GetExampleClass
    {
        get
        {
            return ec ?? GetComponent<ExampleClass>();
        }
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question