mercredi 29 novembre 2023

How to determine if `object?` is nullable? [duplicate]

The following test fails:

#nullable enable
using System;
using FluentAssertions;
using Xunit;

public class TypeExtensionsTests
{
    [Fact]
    public void TestIsNullable()
    {
        object? o = new();
        var type = o.GetType();

        bool isNullable = type.IsNullable();

        isNullable.Should().BeTrue();
    }
}

public static class TypeExtensions
{
    public static bool IsNullable(this Type type)
    {
        return Nullable.GetUnderlyingType(type) != null;
    }
}

How to reliably establish that a Type instance is actually a nullable type?

This question does not answer my question, since the top answer is the implementation of the failing test.





Aucun commentaire:

Enregistrer un commentaire