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.