Skip to content

[MaybeNull]: Cannot implement a generic method with a "default" return value with nullable references #30953

@ssg

Description

@ssg

I'm trying to implement methods that return an optional of a given type T but get a compiler error. Changing return type to T? only changes the error.

I understand why compiler provides that error, it makes sense, but I have no idea how I can get around it in the world of nullable references. Should I change the design of such methods?

Version Used:
Roslyn_Nullable_References_Preview_09112018

Steps to Reproduce:

        public static T FirstOrDefault<T>(this IList<T> list)
        {
            if (list.Count == 0)
            {
                return default; // CS8625
            }
            return list[0];
        }

Expected Behavior:
The code compiles fine without nullable references. I'd expect it to work the same.

Actual Behavior:
Compiler error CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter.

Metadata

Metadata

Assignees

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions