Convince static null check when calling function as parameter,

256 Views Asked by At

EDIT: My gist seems to work, ie, I dont get any problems... so I guess the problem lies elsewhere. Ill keep this post open for a short while, then close it

I have this class Result

public class Result<T>
{
      public T? Data { get; private set; }      
      public Result(T? data) => Data = data;          
      public Result<T> Validate(Func<T, bool> validator, Func<T, string> errorMessage)
      {
          if (this.Data != null)
          {
               return validator(this.Data!)
                  ? this
                  : Result.Error<T>(errorMessage(this.Data!));
          }
          return this;
      }
}

public static class Result
{
    public static Result<T> From<T>(T? data) => new Result<T>(data);
    public static Result<T> Error<T>(string message) => throw null!;
}

I want to write

Result result = Result.From("hello");
               .Validate(t => t != "world", t => "You cant write world")

This works, but I get that squiggly line on the variable t in the Validate-call, saying t might be null, even though I make a null-check (and bang operator).

Is there any way to convince the static null checker that t cant be null here? (null check is done in From-function, but that is irrelevant here.)

1

There are 1 best solutions below

0
On

...ok ... it was my fault (of course)

On creation I took T data, which if you send in a nullable object, returned a nullable object. But if I instead declared to take a nullable object and returned a non-object, it helped analysis to be sure what to pass through. Thanks for the help, It wasnt really helpable with the information I provided, since it was in the creation (From()), sorry about that

I changed from this

 public static Result<T> From<T>(T data, string? errorMessage = null) =>
        data is null
            ? Error<T>(errorMessage ?? $"Parameter value is null in Result.From(), expecting a non-null {typeof(T).Name}")
            : Ok(data);

to this:

 public static Result<T> From<T>(T? data, string? errorMessage = null) =>
        data is null
            ? Error<T>(errorMessage ?? $"Parameter value is null in Result.From(), expecting a non-null {typeof(T).Name}")
            : Ok(data);