I am learning about the ins-and-outs of nullable reference types in C# 8.0
Whilst reading this blog about nullable reference types, I was left a bit puzzled by the following example.
public static HandleMethods
{
public static void DisposeAndClear([DisallowNull] ref MyHandle? handle)
{
...
}
}
The author shows how a [DisallowNull]
attribute can be used in this case. However, my query is why would you need the attribute here at all? Is this code not the same?
public static HandleMethods
{
public static void DisposeAndClear(ref MyHandle handle)
{
...
}
}
By removing the attribute, and the ?
at the end of MyHandle
, would this be a like-for-like alternative?
EDIT:
Thanks to UnholySheep, I believe I understand this now.
public static void DisposeAndClear([DisallowNull] ref MyHandle? handle)
{
handle = null;
}
When calling this version of the function, handle
cannot be null going in. However, it could be set to null inside the function, so when the function returns, anything using handle
needs to check whether handle
is null.
Based on the discussion in the comments
The important part of the blog post is the following
Typical use for this API is that we have a non-null instance that we pass by reference, but when it is cleared, the reference is null
This means that the method accepts a non-null
object but at some point in the method handle
will be set to null
As setting handle
to null
is not allowed in the version which takes a non-nullable reference as parameter (ref MyHandle handle
) the other version has to be used
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With