Search Unity

What does the "?" do when added to the end of a getter call?

Discussion in 'Scripting' started by SpiderJones, Oct 31, 2019.

  1. SpiderJones

    SpiderJones

    Joined:
    Mar 29, 2014
    Posts:
    244
    I saw code that looked like this
    Code (CSharp):
    1. aGetter?.MethodInReturnedObject();
    What does the "?" do here?

    Thanks!
     
  2. JasonBricco

    JasonBricco

    Joined:
    Jul 15, 2013
    Posts:
    956
    It checks if aGetter is null or not. If not, then it calls the function. If yes, it doesn't.

    That's the null-conditional operator added in C# 6.
     
    SpiderJones likes this.
  3. SpiderJones

    SpiderJones

    Joined:
    Mar 29, 2014
    Posts:
    244
    Thanks!
     
  4. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    Note that you probably shouldn't be using that operator on most Unity objects, because Unity uses "pretend" null values for certain things that aren't really null for purposes of that operator.