Do we need the var keyword? And what is a 'RaycastHit?'?

I used ‘RaycastHit?’ as a type, rather than ‘var’, and it works fine. I just reference the value, or cast to RaycastHit if non-null. So my questions are

  • What’s the advantage of using ‘var’ here in cameraraycaster script? It seems to me to just mask the type from the software developer, which really smells of bad code to me.

  • Is ‘RaycastHit?’ a type in itself, or some weird modification of ‘RaycastHit’ ? My Visual Studio Code IDE highlights ‘RaycastHit?’ instead of ‘RaycastHit?’, which confused me because I thought the compiler will treat RaycastHit? as a new type entirely, like this almost-valid C# pseudocode:

class RaycastHit?{

    bool _isNull;
    RaycastHit _hit;
    
    public selfValue {  // pseudocode
            get { if (_isNull) return null; return _hit; }
            set { if (value == null) {_isNull = true;}  
                  else {_hit = value; _isNull = false;}
            }
    }

}

In my opinion var is bad. Other will disagree. I like to know what type my variables are at design time NOT run time.

RaycastHit? is not a type at all, the ? tells the compiler that it can be NULL, so your method can return a NULL or a RaycastHit.

Privacy & Terms