Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using [DisallowNull] vs non-nullable reference type

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.

like image 584
Jason Evans Avatar asked Sep 29 '20 07:09

Jason Evans


1 Answers

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

like image 54
UnholySheep Avatar answered Oct 23 '22 04:10

UnholySheep