User-defined null on structs #7602
Replies: 3 comments 18 replies
-
@RikkiGibson has looked at things around this area before. There's also several related issues: #146, https://github.com/dotnet/csharplang/blob/main/meetings/2020/LDM-2020-07-01.md#non-defaultable-struct-types, #1981, and #2019. |
Beta Was this translation helpful? Give feedback.
-
Here is one possible design. The literal |
Beta Was this translation helpful? Give feedback.
-
I'm surprised that |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
In the advent of ref structs, there are now many use cases for which the developer may want to define what "null" means for their struct. For example, users today can write
null
in place of an expression that evaluates toReadOnlySpan<T>
but this is only because of an implicit operator converting arrays to spans, and converting a null array to a span yields an empty, nullref span. It is likely that the majority of users do not know that this is hownull
on spans work, and therefore only care for the presence ofnull
for these types of structs.There may be use cases where user types are unable to wield
null
as-is as there may be multiple implicit operators thatnull
could be applicable for.This suggestion is for adding a way for users to control what occurs when a developer writes
null
for their structs.Spit-balling here:
For obvious reasons this should not be allowed for classes.
Motivating Use Case
In SilkX we have wrapper types representing references/pointers, that are implicitly convertible from strings and arrays.
But this isn't the only case, again see Span. The only reason this works today is because of the array operator which feels more of a "happy accident" than a fact known from before the API was designed and/or prototyped.
Our Dirty Workaround
SilkX defines its own little domain specific language extensions, and
global using static
is used to define anullptr
keyword (actually a static property that returns aNullPtr
that implicitly converts to all of these types. JIT does its thing and inlines all of it).Usage example:
Obviously this is extremely cursed, but this is the only way we could think to achieve the developer experience we're after.
Beta Was this translation helpful? Give feedback.
All reactions