Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

v3.0.0 GetValueOrDefault() returns nullable when default value is not nullable #570

Open
seangwright opened this issue Sep 25, 2024 · 1 comment

Comments

@seangwright
Copy link
Contributor

seangwright commented Sep 25, 2024

Environment

  • .NET 8, C# 12, VS Code, C# DevKit
  • I have NRT enabled and warnings as errors.
  • Here are the types of the properties in the following example

Types

  • WebPageMetaTitle - string
  • BlogPostPageBlogPostContent - IEnumerable<T>
  • ListableItemTitle - string

Here's my custom extension

public static Maybe<string> MapNullOrWhiteSpaceAsNone(this Maybe<string> value) =>
        value.Bind(v => string.IsNullOrWhiteSpace(v) ? Maybe.None : Maybe.From(v));

Example

Now I'm seeing an error with .GetValueOrDefault() when I provide it a non-null default.

string metaTitle = Maybe
            .From(WebPageMetaTitle)
            .MapNullOrWhiteSpaceAsNone()
            .IfNoValue(BlogPostPageBlogPostContent
                .TryFirst()
                .Bind(c => Maybe.From(c.ListableItemTitle).MapNullOrWhiteSpaceAsNone()))
            .GetValueOrDefault(""); // ERROR: Converting null literal or possible null value to non-nullable type.

Workarounds

It is unfortunate that I now need to do one of the following

  1. .GetValueOrDefault("") ?? "";
  2. Create my own extension .GetValueOrDefaultNotNull(""); that is typed as public T GetValueOrDefaultNotNull(T defaultValue = default(T))
  3. .GetValueOrDefault("")!;
  4. .TryGetValue(out string? val) ? val : "";
  5. .Match(v => v, _ => ""); - for some reason the overload resolution no longer works here and I get the compilation error Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
@vkhorikov
Copy link
Owner

Could you try v3.1.0 and let me know if this is fixed? Made some adjustments to that method.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants