What does the ? operator do in C#?

42 Views Asked by At

I'm looking through this piece of code: https://github.com/aras-p/UnityGaussianSplatting/blob/main/package/Runtime/GaussianSplatRenderer.cs and line 65 has,

m_CommandBuffer?.Dispose(); 

Which I don't understand, because the object it is using is m_CommandBuffer. So what is this "?" operation that fits between the object and .Dispose();? It seems to be at the language level, but I can't find reference to it. Thanks.

1

There are 1 best solutions below

1
TomTom On

It is a null resolution. If m_CommandBuffer is null, no exception is thrown but the processing stops (dispose is not called).

This is identical and shorter to:

if (m_CommandBuffer != null) m_CommandBuffer.Dispose();

This was added years ago, together with ??, which is null chaining:

m_CommandBuffer = Functioncall() ?? throw new InvalidOperationException

if Function call returns null, the part after ?? is assigned (or inf this case thrown).

Learn full C# syntax - lots of stuff like that "hidden" in the documentation. More every language version.