You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Nullness issue - unclear how to deal with 'T | null interop #17734
Some C# public API's currently expose 'T | null in signature, while F# adds additional constraints per RFC. With F# it should be possible to:
Consume such types
Expose such types (without additional constraints)
It seems that neither of those points is posssible with .NET 9 RC1. Real application is Oxpecker library where I'm unable to express deserialize method signature to match C# underlying call.
Choose one or more from the following categories of impact
Unexpected nullness warning (false positive in nullness checking, code uses --checknulls and langversion:preview).
Missing nullness warning in a case which can produce nulls (false negative, code uses --checknulls and langversion:preview).
Breaking change related to older null constructs in code not using the checknulls switch.
Breaking change related to generic code and explicit type constraints (null, not null).
Type inference issue (i.e. code worked without type annotations before, and applying the --checknulls enforces type annotations).
C#/F# interop issue related to nullness metadata.
Other (none of the categories above apply).
Operating System
Windows (Default)
What .NET runtime/SDK kind are you seeing the issue on
.NET SDK (.NET Core, .NET 5+)
.NET Runtime/SDK version
No response
Reproducible code snippet and actual behavior
openSystem.Text.Jsonletx= JsonSerializer.Deserialize<int>("")// x has type int | null
Possible workarounds
I couldn't find any workarounds
Reacted by Friedrich von Never, Adrián Montesinos González and John Wostenberg
varx=ctx.Request.ReadFromJsonAsync<int>().Result;// x is of type intvary=ctx.Request.ReadFromJsonAsync<string>().Result;// y is of type string?
Declaration:
public static ValueTask<TValue?> ReadFromJsonAsync<TValue>(
this HttpRequest request,
CancellationToken cancellationToken = default(CancellationToken))
in class Microsoft.AspNetCore.Http.HttpRequestJsonExtensions
| null is only about nullable reference types, if you declare it as a type, it is inferred as reference. For nullable value types System.Nullable should be used, so adding a constraint is expected.
This is a consequence of the C# code misleading about the return type - because the returned value is not nullable in the System.Nullable sense (as it would be in C# in a non-generic context), the nullness simply isn't there at all if instantiated by value type.
Without knowing the implementation, one could assume that the C# code returns null for reference types and default for value types - without any indication to the caller that a default value was chosen. It will not crash with NRE, but it might be another source of issues if the absence of information is not communicated via the type system.
Intention-revealing workaround would be to wrap this method in a dedicated generic call restricted to value types, and dealing with absence of information in value types explicitly.
I do understand that C# does allow (T | null) in generic code without it having the right meaning for value types ;; a compromise taken to allow coexistence of NRTs and value types. I do not believe F# should repeat exactly the same, at least not without an approved suggestion.
My suggestion for now would be to expose two methods:
Deserialise for reference types returning T | null.
Deserialise for value types returning Nullable of T (or other container for absence of information).
A bigger ask would be the unification of NRTs and NVTs in the type system already. However, since they have different representations at runtime (none for NRTs, System.Nullable for NVTs) this would still not work across interop boundary. But assuming an approved suggestion and RFC, I think an implementation for F#-inlined generic code could make this work (ignoring the efforts for now).
A bigger ask would be the unification of NRTs and NVTs in the type system already.
I have discussed it with Don numerous times, and it was decided that we don't want to do it. We don't want to encourage people to use nullable reference types let alone unify nullables under one syntactic structure. It will make it harder to understand what is going on and will be hiding concrete types behind the new construct. In future this can be partially (on the declaration and params side) remediated when we introduce anonymous unions.
That said, I suggest creating a new separate language suggestion w.r.t constraint-by-default, S.Nullable<_> and their interop/unification with nullable references feature.
A bigger ask would be the unification of NRTs and NVTs in the type system already.
I have given it a thought and I think this is not required, the ability to speficify or in costraints should be sufficient:
'T when('T:notnulland 'T:notstruct)or 'T:struct
As far as I remember while this can't be done in user code, it still can be used in FSharp.Core, so defining
typeNRT<'Twhen('T:not null and 'T:not struct)or'T:struct>= 'T
might work, i.e. it will allow exposing the same type as C# exposes now
That said, I suggest creating a language suggestion w.r.t constraint-by-default, S.Nullable<_> and their interop with nullable references feature.
This still doesn't resolve the consuming part right now, e.g. once you use this API you'll get int | null type derived while it seems that this should be impossible. So this interop case should be handled anyway.
My suggestion for now would be to expose two methods:
Deserialise for reference types returning T | null.
Deserialise for value types returning Nullable of T (or other container for absence of information).
This is very unpleasant from consumer's view and also doesn't work
To be clear - I don't know what is the implementation underneath (when null is returned for ref types), I just want to preserve the same types that existing API returns
Representing both nullable reference type and value type in IL is tricky, and what C# does is it just pretends that null is not there from the flow analysis standpoint. In F# | null is possible only with reference types, hence the constraint is for correctness.
Constraint inference was part of design decision, suggestion is needed to omit it.
With this issue I don't suggest removing constraints or do any other particular suggestion, it is to point out that currently it is impossible to normally use popular .NET libraries (which is undesired behavior), and this ticket shouldn't be closed until the issue is resolved. I agree that the concrete suggestion "how to fix it" might go into suggestion repo, but it's not a reason to close the unresolved issue.
It is currently not actionable for us here. It needs a specific suggestion of what the behaviour currently and what it should be. Suggestions repo is an ideal place for something like it, as most of the discusssions happen there.
Ok sounds like "currently not a bug", but before closing the issue users like me should get an answer - what to do in current situation. Is the currently suggested solution to disable nullness warnings?
Ok sounds like "currently not a bug", but before closing the issue users like me should get an answer - what to do in current situation. Is the currently suggested solution to disable nullness warnings?
I would say so, or use optional types where possible
I do think there is an issue here with the way F# consumes the metadata for generic 'T | null, although it only really seems to affect the displayed (pseudo-)type, not the actual (?) (pseudo-)type.
// Tooling shows x: int | null. This could never actually be null when 'T is a value type.letx= Unchecked.defaultof<HttpContext>.Request.ReadFromJsonAsync<int>().Result
// Tooling shows y: int | null. No warning is given.lety= x +2// Tooling shows z: int. No warning is given.letz=2+ x
Contrast that against
letx:string | null=null// Warning FS3261. y is inferred to be string | null (even though it will never actually be null due to how + works in F#).lety= x +""// No warning. z is inferred to be string.letz=""+ x
At the very least, it's confusing.
I can see the logic behind the C# approach: T? indicates that the value could be null — if T is instantiated to a reference type or System.Nullable.
I think it would make sense for F# to do the same thing here — or at least for the tooling not to show impossible (and inaccurate) types like int | null. That part definitely seems like a bug to me.
I will check that.
It should definitely be possible to instantiate such a C#-defined generict type/method with a value type, and work with it without getting warnings.
The display follows the original signature coming from IL, but at this point the type application can remove the constraint.
What remains impossible is authoring null-allowing generic code supporting both reference and value types (authoring does include wrappers). Which does not prevent using them with concrete non-generic instances.
(if a suggestion is created - a strong point should be raised against modelling the absence of information with default for F#-created generic code that includes value types. Doing that blocks that user from determining if the information was really missing, or has a regular value which happens to be equal to default.
If the solution would be to convert such null-allowing generic code into option/voption, the modelling problem disappears)
What remains impossible is authoring null-allowing generic code supporting both reference and value types (authoring does include wrappers). Which does not prevent using them with concrete non-generic instances.
I would add that authoring null-disallowing generic code is also impossible. Any generic code that consumes C# library with generic T? parameter is impossible without disabling warnings. In the following case I'd be ready to expose null-disallowing generic type (with current constraints) by adding additional null check in function body, but this is not possible, since all null-checking functions are constrained.
// possible solution which is currently impossiblelettryDeserialize<'T>(value:string)=trymatch JsonSerializer.Deserialize<'T>(value)with| Null -> None
| NonNull x -> Some x
with ex ->
None
That is correct for the new nullness checking functions.
Some null checking can be done with boxing, either explicit via box or implicit via obj.ReferenceEquals(value,null) - but that is obviously not meaningful to do in the case of value types.
The proposal could include some relaxed conditions + optimizations for built-in functions specifically for consumption of null-allowing unconstrained generic code.
E.g. I could imagine a version similar to "Option.ofObj", which would be a no-op in case of value types (the emited IL could be a typetest on the generic T argument, which JIT would optimize away at time of generic instantiation).
Just ran into this in the wild but from the other direction, while trying to implement an interface that expects you to author a method with 'T | null as the return type. Specifically, IEventContext from SocketIO (and <WarningsAsErrors>$(WarningsAsErrors);FS3261</WarningsAsErrors> set in the project file).
letfakeContext()={new IEventContext with// can't implement this without getting hit with FS3261memberthis.GetValue<'T>(_index:int):'T = raise (NotImplementedException())// other attempts:// member this.GetValue<'T>(_index: int) : 'T | null = raise (NotImplementedException())// member this.GetValue<'T when 'T : not null and 'T : not struct>(_index: int) : 'T | null = raise (NotImplementedException())// member this.GetValue<'T when 'T : null>(_index: int) : 'T = raise (NotImplementedException())// ...}
At least in F# 10 we have a better workaround in scoped #nowarn:
And in simple instances like this where you don't actually need to reference the generic parameter at all, you can actually just omit it enitrely (leaving it implicit):
In my specific case, it is a test fake that doesn't need a real implementation (hence the raise - no return at all)
In the library itself, the two real implementations (NewtonsoftJsonAckMessage and SystemJsonAckMessage) ultimately call Deserialize<T> (from the respective libraries) - it's basically just the exact same scenario that @Lanayx raises, but with inverted control
Probably a relatively niche situation but I figured I'd document it here. If this is left unsupported, it might at least be nice to touch on that in the official docs / articles. I spend a good chunk of time trying to figure out how to appease the compiler, and after moving on it took me a little while to dig up this thread. I would imagine that most people give up earlier and just assume the compiler is broken
I will prototype an addition to the Unchecked module to solve those cases.
There are some rough edges (e.g. when you have such unconstrained T? value, it still must not be passed to functions working with regular null-supporting values. Because the call might want to make a mutable cell, and assign null to it - and crash at runtime for structs)
Activity
Lanayx commentedon Sep 15, 2024
Adding C# code for reference:
Declaration:
vzarytovskii commentedon Sep 15, 2024
| nullis only about nullable reference types, if you declare it as a type, it is inferred as reference. For nullable value types System.Nullable should be used, so adding a constraint is expected.T-Gro commentedon Sep 15, 2024
This is a consequence of the C# code misleading about the return type - because the returned value is not nullable in the System.Nullable sense (as it would be in C# in a non-generic context), the nullness simply isn't there at all if instantiated by value type.
Without knowing the implementation, one could assume that the C# code returns null for reference types and default for value types - without any indication to the caller that a default value was chosen. It will not crash with NRE, but it might be another source of issues if the absence of information is not communicated via the type system.
Intention-revealing workaround would be to wrap this method in a dedicated generic call restricted to value types, and dealing with absence of information in value types explicitly.
I do understand that C# does allow (T | null) in generic code without it having the right meaning for value types ;; a compromise taken to allow coexistence of NRTs and value types. I do not believe F# should repeat exactly the same, at least not without an approved suggestion.
T-Gro commentedon Sep 15, 2024
My suggestion for now would be to expose two methods:
Deserialise for reference types returning T | null.
Deserialise for value types returning Nullable of T (or other container for absence of information).
A bigger ask would be the unification of NRTs and NVTs in the type system already. However, since they have different representations at runtime (none for NRTs, System.Nullable for NVTs) this would still not work across interop boundary. But assuming an approved suggestion and RFC, I think an implementation for F#-inlined generic code could make this work (ignoring the efforts for now).
vzarytovskii commentedon Sep 15, 2024
I second that
vzarytovskii commentedon Sep 15, 2024
I have discussed it with Don numerous times, and it was decided that we don't want to do it. We don't want to encourage people to use nullable reference types let alone unify nullables under one syntactic structure. It will make it harder to understand what is going on and will be hiding concrete types behind the new construct. In future this can be partially (on the declaration and params side) remediated when we introduce anonymous unions.
That said, I suggest creating a new separate language suggestion w.r.t constraint-by-default, S.Nullable<_> and their interop/unification with nullable references feature.
Lanayx commentedon Sep 15, 2024
I have given it a thought and I think this is not required, the ability to speficify
orin costraints should be sufficient:As far as I remember while this can't be done in user code, it still can be used in FSharp.Core, so defining
might work, i.e. it will allow exposing the same type as C# exposes now
This still doesn't resolve the consuming part right now, e.g. once you use this API you'll get
int | nulltype derived while it seems that this should be impossible. So this interop case should be handled anyway.This is very unpleasant from consumer's view and also doesn't work

To be clear - I don't know what is the implementation underneath (when null is returned for ref types), I just want to preserve the same types that existing API returns
11 remaining items
vzarytovskii commentedon Sep 25, 2024
Representing both nullable reference type and value type in IL is tricky, and what C# does is it just pretends that null is not there from the flow analysis standpoint. In F# | null is possible only with reference types, hence the constraint is for correctness.
Lanayx commentedon Sep 25, 2024
With this issue I don't suggest removing constraints or do any other particular suggestion, it is to point out that currently it is impossible to normally use popular .NET libraries (which is undesired behavior), and this ticket shouldn't be closed until the issue is resolved. I agree that the concrete suggestion "how to fix it" might go into suggestion repo, but it's not a reason to close the unresolved issue.
vzarytovskii commentedon Sep 25, 2024
It is currently not actionable for us here. It needs a specific suggestion of what the behaviour currently and what it should be. Suggestions repo is an ideal place for something like it, as most of the discusssions happen there.
Lanayx commentedon Sep 25, 2024
Ok sounds like "currently not a bug", but before closing the issue users like me should get an answer - what to do in current situation. Is the currently suggested solution to disable nullness warnings?
vzarytovskii commentedon Sep 25, 2024
I would say so, or use optional types where possible
brianrourkeboll commentedon Sep 25, 2024
I do think there is an issue here with the way F# consumes the metadata for generic
'T | null, although it only really seems to affect the displayed (pseudo-)type, not the actual (?) (pseudo-)type.Contrast that against
At the very least, it's confusing.
I can see the logic behind the C# approach:
T?indicates that the value could be null — ifTis instantiated to a reference type orSystem.Nullable.I think it would make sense for F# to do the same thing here — or at least for the tooling not to show impossible (and inaccurate) types like
int | null. That part definitely seems like a bug to me.T-Gro commentedon Sep 26, 2024
I will check that.
It should definitely be possible to instantiate such a C#-defined generict type/method with a value type, and work with it without getting warnings.
The display follows the original signature coming from IL, but at this point the type application can remove the constraint.
What remains impossible is authoring null-allowing generic code supporting both reference and value types (authoring does include wrappers). Which does not prevent using them with concrete non-generic instances.
T-Gro commentedon Sep 26, 2024
(if a suggestion is created - a strong point should be raised against modelling the absence of information with
defaultfor F#-created generic code that includes value types. Doing that blocks that user from determining if the information was really missing, or has a regular value which happens to be equal to default.If the solution would be to convert such null-allowing generic code into option/voption, the modelling problem disappears)
Lanayx commentedon Sep 26, 2024
I would add that authoring null-disallowing generic code is also impossible. Any generic code that consumes C# library with generic
T?parameter is impossible without disabling warnings. In the following case I'd be ready to expose null-disallowing generic type (with current constraints) by adding additional null check in function body, but this is not possible, since all null-checking functions are constrained.T-Gro commentedon Sep 27, 2024
That is correct for the new nullness checking functions.
Some null checking can be done with boxing, either explicit via
boxor implicit viaobj.ReferenceEquals(value,null)- but that is obviously not meaningful to do in the case of value types.The proposal could include some relaxed conditions + optimizations for built-in functions specifically for consumption of null-allowing unconstrained generic code.
E.g. I could imagine a version similar to "Option.ofObj", which would be a no-op in case of value types (the emited IL could be a typetest on the generic T argument, which JIT would optimize away at time of generic instantiation).
jwosty commentedon Aug 5, 2026
Just ran into this in the wild but from the other direction, while trying to implement an interface that expects you to author a method with
'T | nullas the return type. Specifically, IEventContext from SocketIO (and<WarningsAsErrors>$(WarningsAsErrors);FS3261</WarningsAsErrors>set in the project file).The C# interface (shortened):
F# implementation:
At least in F# 10 we have a better workaround in scoped
#nowarn:And in simple instances like this where you don't actually need to reference the generic parameter at all, you can actually just omit it enitrely (leaving it implicit):
Though of course this won't work in all situations.
I'll agree though that C#'s choice here is somewhat unfortunate
T-Gro commentedon Aug 6, 2026
How would a typical implementation derive the return value?
via
Unchecked.defaultof<T>?i.e. we would want that to conform
T?no matter the structness/meaningfullness?jwosty commentedon Aug 6, 2026
In my specific case, it is a test fake that doesn't need a real implementation (hence the
raise- no return at all)In the library itself, the two real implementations (NewtonsoftJsonAckMessage and SystemJsonAckMessage) ultimately call
Deserialize<T>(from the respective libraries) - it's basically just the exact same scenario that @Lanayx raises, but with inverted controlProbably a relatively niche situation but I figured I'd document it here. If this is left unsupported, it might at least be nice to touch on that in the official docs / articles. I spend a good chunk of time trying to figure out how to appease the compiler, and after moving on it took me a little while to dig up this thread. I would imagine that most people give up earlier and just assume the compiler is broken
T-Gro commentedon Aug 7, 2026
I will prototype an addition to the
Uncheckedmodule to solve those cases.There are some rough edges (e.g. when you have such unconstrained
T?value, it still must not be passed to functions working with regular null-supporting values. Because the call might want to make a mutable cell, and assignnullto it - and crash at runtime for structs)Lanayx commentedon Aug 8, 2026
Here's a workaround that I've used for my case:
https://github.com/Lanayx/Oxpecker/blob/20b71802ef71b708ebe85c6860f20fad8ccb55ec/src/Oxpecker/Serializers.fs#L60