Comparing a ref to null? #2401
-
I'm being dumb I'm sure but I have a method that returns a ref to an unmanaged struct. ref var block_ref = ref SomeMethod(); I want to now write: if (block_ref == null)
... But I can't get a clean compile no matter what I try... |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments
-
@Korporal You might want to consider gitter.im/dotnet/csharplang for quick questions like this. For the above, could you explain how you would get null in the first place in block_ref? |
Beta Was this translation helpful? Give feedback.
-
You can only get a Likewise, you need to use the |
Beta Was this translation helpful? Give feedback.
-
@CyrusNajmabadi - OK You're right, I've not been to gitter and I guess I should take a look. |
Beta Was this translation helpful? Give feedback.
-
Yes and that's what this is, under the hood the method attempts to get some memory (from outside the AppDomain but inside the process address space) if it is not able to then ordinarily we'd return a null pointer (for example if this in C). |
Beta Was this translation helpful? Give feedback.
-
I've moved to gitter... |
Beta Was this translation helpful? Give feedback.
You can only get a
null ref
(that is a ref which is null; rather than a reference to a null) via unsafe means today. For example, usingUnsafe.AsRef<T>(null)
or via interop code involving ref returns.Likewise, you need to use the
Unsafe
class to check if you have anull ref
.